All date and time APIs are within the DateTime module.
Formatted output for the 1st perioddatetime-= string
Import datetime
now = Datetime.datetime.now ()
Now.strftime ('%y-%m-%d%h:%m:%s ')
Output
' 2015-04-07 19:11:21 '
Strftime is an instance method of a DateTime class.
string = DateTime
Import datetime
T_str = ' 2015-04-07 19:11:21 '
D = datetime.datetime.strptime (T_str, '%y-%m-%d%h:%m:%s ')
Strptime is a static method of a DateTime class.
There is a Timedelta class in the DateTime module, where objects of this class are used to represent a time interval, such as a two-day # period or a time difference.
2. Date arithmeticDate comparison Operations
There is a Timedelta class in the DateTime module, where objects of this class are used to represent a time interval, such as a difference of two dates or times.
Construction Method:
Import datetime
Datetime.timedelta (days=0, seconds=0, Microseconds=0, Milliseconds=0, Minutes=0, hours=0, weeks=0)
All parameters have a default value of 0, which can be either int or float, positive or negative.
The corresponding time value can be obtained by timedelta.days, Tiemdelta.seconds and so on.
An instance of the Timedelta class, which supports addition, subtraction, multiplication, and other operations, is also an example of the Timedelta class. Like what:
Import datetime
Year = Datetime.timedelta (days=365)
Ten_years = year *10
Nine_years = Ten_years-year
The date, time, and DateTime classes also support the addition and subtraction of Timedelta.
datetime1 = datetime2 + Timedelta
Timedelta = datetime1-datetime2
In this way, it is convenient to implement some functions.
How many days do two dates differ
Import datetime
D1 = Datetime.datetime.strptime (' 2015-03-05 17:41:20 ', '%y-%m-%d%h:%m:%s ')
D2 = Datetime.datetime.strptime (' 2015-03-02 17:41:20 ', '%y-%m-%d%h:%m:%s ')
Delta = d1-d2
Print Delta.days
Output: 3
today's n days after the date
Import datetime
now = Datetime.datetime.now ()
Delta = Datetime.timedelta (days=3)
N_days = Now + Delta
Print N_days.strftime ('%y-%m-%d%h:%m:%s ')
Output:
2015-04-10 19:16:34
The benefit of datetime is that convenient time operations such as endtime-startime can be achieved, which is very convenient when the time duration is calculated.
Reference articles
Python Date-time function
Python Date-time function processing