1. Date output formatting
All date and time APIs are within the DateTime module.
1. DateTime = = string
now = Datetime.datetime.now () now.strftime ('%y-%m-%d%h:%m:%s')# output 2012-03-05 16:26:23.870105
Strftime is an instance method of a DateTime class.
2. String = DateTime
' 2012-03-05 16:26:23 ' '%y-%m-%d%h:%m:%s')
Strptime is a static method of a DateTime class.
2. Date comparison operation
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:
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:
Year = Timedelta (days=365= year *10= ten_years-year
The date, time, and DateTime classes also support the addition and subtraction of Timedelta.
datetime1 = datetime2 +/-= Datetime1-datetime2
In this way, it is convenient to implement some functions.
1. The number of days between two dates.
D1 = datetime.datetime.strptime ('2012-03-05 17:41:20'%y-%m-%d%h:%m:%s '= datetime.datetime.strptime ('2012-03-02 17:41:20' %y-%m-%d%h:%m:%s'= d1- d2print delta.days
Output: 3
2. Today's date of N days.
now == Datetime.timedelta (days=3= now + Deltaprint n_days.strftime (' %y-%m-%d%h:%m:%s ')
Output: 2012-03-08 17:44:50
#Coding=utf-8ImportDatetimenow=Datetime.datetime.now ()Print Now#Converts a date to a string datetime = = stringPrintNow.strftime ('%y-%m-%d%h:%m:%s') T_str='2012-03-05 16:26:23'#Convert a string to a date string = DateTimeD=datetime.datetime.strptime (T_STR,'%y-%m-%d%h:%m:%s')PrintD#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. #calculate the interval of two datesD1 = Datetime.datetime.strptime ('2012-03-05 17:41:20','%y-%m-%d%h:%m:%s') D2= Datetime.datetime.strptime ('2012-03-02 17:41:20','%y-%m-%d%h:%m:%s') Delta= d1-D2Printdelta.daysPrintDelta#The date of today's N days. now=datetime.datetime.now () Delta=datetime.timedelta (days=3) N_days=now+DeltaPrintN_days.strftime ('%y-%m-%d%h:%m:%s')
Python date plus and minus operations