Python programming and development-date operation instance analysis, python programming and development
This example describes the date operations for python programming and development. We will share this with you for your reference. The details are as follows:
The databases for date operations in python include:
Import datetime
Import time
For date formatting information, refer to the official API:
Time. strftime
Datetime
Below is my demo:
# Datetimeimport datetime # current date now = datetime. datetime. now () print (now. strftime ('% Y-% m-% d % H: % M: % s') print (now. strftime ('% Y-% m-% D') # string convert to datetimetime_str = '2017-07-29 01:05:00' str _ convert_2_time = datetime. datetime. strptime (time_str, '% Y-% m-% d % H: % M: % s') print (str_convert_2_time) # compare the number of days between two dates time_strA = '2017-07-29 01:05:00 'time _ strB = '2017-08-29 01:05:00' day = datetime. datetime. strptime (time_strA, '% Y-% m-% d % H: % M: % s') day2 = datetime. datetime. strptime (time_strB, '% Y-% m-% d % H: % M: % s ') sub_day = day2-dayprint ('{0} and {1} differ by {2} days '. format (time_strA, time_strB, str (sub_day.days) # date n_days = 4now = datetime for the next n days. datetime. now () my_date = datetime. timedelta (days = n_days) n_day = now + my_dateprint ('the Date of {0} days from today is :'. format (n_days) print (n_day.strftime ('% Y-% m-% d % H: % M: % s '))
Running effect:
Python 3.3.2 (v3.3.2: d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32Type "copyright", "credits" or "license () "for more information. >>> ================================== RESTART ======== ==========================================>>> 2013-07-29 01: 48: 162013-07-292013-07-29 01:05:00 01:05:00-002013-07-29 01:48:16 and 2013-08-29 are different 31 days. The four days from today are: >>>
I hope this article will help you with Python programming.