Official documents
Http://python.usyiyi.cn/translate/python_352/library/datetime.html
code example
fromDatetimeImportDatetimenow=DateTime.Now ()Print("Year:%s"%now.year)Print("Month:%s"%now.month)Print("Day:%s"%now.day)Print("When:%s"%now.hour)Print("points:%s"%Now.minute)Print("seconds:%s"%Now.second)Print("milliseconds:%s"%Now.microsecond)Print("Week:%s"% Now.weekday ())#Monday to Sunday 0-6Print("Week:%s"% Now.isoweekday ())#Monday to Sunday 1-7Print("Date:%s"%now.date ())Print("Time:%s"%now.time ())Print("kilometer ordinal:%s"% now.toordinal ())#the kilometer ordinal of the 00001-year January 1 is the kilometer ordinal of the 1,00001 year January 2 is 2
1. Get the current date and time
fromDatetimeImportDatetimedt= DateTime (year=2017, month=6, day=27, hour=16, minute=19, second=52)Print(Dt.strftime ("%y-%m-%d%h:%m:%s"))#The%Y is represented by a 0-filled decimal number with a century 0001, 0002, ...,, ..., 9998, 9999#%y a year with a decimal number of 0 fills, with no century .#%m The month of a decimal number filled with 0 , in ...#%d the date in the month represented by a 0-populated decimal number in the months of the day .#%H Hour (24-hour system) in 0-filled decimal digits, 03...23, xx ,#%I Hour (12-hour system) in decimal number with 0 padding, ...,#%M minutes by 0 populated decimal digits, 02...59,#%s The number of seconds represented by a 0-padded decimal number. 02...59#%j The date in the year represented by a 0-filled decimal number 001,002,...,366#the literal value of the percent '% ' character
2. Date-time objects formatted as strings
Note: The parameters of the Strftime () method may be wrong when they contain Chinese, there are two solutions, and the second one is recommended.
fromDatetimeImportdatetime fromDatetimeImportTimedelta#1. Add a specified time to a dateToday =Datetime.today ()Print(Today + Timedelta (Days=1))#+ 1 daysPrint(Today + Timedelta (days=-1))#-1 days = Today-timedelta (Days=1)Print(Today + Timedelta (Hours=1))#+ 1 hoursPrint(Today + Timedelta (minutes=120))#+ 120 minutes = + 2 hoursPrint(Today + Timedelta (seconds=-10))#-10 secondsPrint(Today + Timedelta (Weeks=1))#+ 1 weeks#2. Two Date subtractionDT1 = DateTime (year=2017, month=6, day=30, hour=13, minute=50) DT2= DateTime (year=2017, month=6, day=30, hour=16, minute=10) Lag_time= DT2-DT1Print(Lag_time.total_seconds ())#time difference, unit: SecondsPrint(Lag_time.total_seconds ()/60)#Time of difference, unit: minutesPrint(Lag_time.total_seconds ()/60/60)#Time of difference, Unit: Hour
3. Date and Time calculation
from Import datetime # use the class method Datetime.strptime (str, format)dt = Datetime.strptime ("2017-6-28 15:56:34" " %y-%m-%d%h:%m:%s " )print(dt)print(type (dt)) # type: <class ' Datetime.datetime ' >
4. String parsing into DateTime object
Python3-datetime module-Date and time