Python The program can handle dates and times in many ways , Converting date formats is a common feature .
Python Provides a time and calendar Module can be used to format date and time .
The time interval is a floating-point decimal in seconds .
Every time stamp comes from 1970 year 1 month 1 Midnight ( Epoch ) How long does it take to express .
Python Of time There are many functions under the module that can convert common date formats . Such as function time.time() Used to get the current timestamp , The following example :
#!/usr/bin/python# -*- coding: UTF-8 -*-import time; # introduce time modular ticks = time.time()print " The current timestamp is :", ticks
The output of the above example :
The current timestamp is : 1459994552.51
Time stamp unit is most suitable for date operation . however 1970 The date before the year cannot be expressed in this way . It's not good to be too far away ,UNIX and Windows Only to 2038 year .
Get the current time
From the dropout of returning floating-point number to time tuple conversion , Just pass the floating-point number to, for example localtime Functions like that .
#!/usr/bin/python# -*- coding: UTF-8 -*-import time
localtime = time.localtime(time.time())print " The local time is :", localtime
The output of the above example :
The local time is : time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=10, tm_min=3, tm_sec=27, tm_wday=3, tm_yday=98, tm_isdst=0)
Get the formatted time
You can choose various formats according to your needs , But the simplest function to get a readable time pattern is asctime():
#!/usr/bin/python# -*- coding: UTF-8 -*-import time
localtime = time.asctime( time.localtime(time.time()) )print " The local time is :", localtime
The output of the above example :
The local time is : Thu Apr 7 10:05:21 2016
Format date
We can use time Modular strftime Method to format the date ,:
time.strftime(format[, t])
#!/usr/bin/python# -*- coding: UTF-8 -*-import time# Format as 2016-03-20 11:45:39 form print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # Format as Sat Mar 28 22:24:24 2016 form print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())
# Convert format string to timestamp a = "Sat Mar 28 22:24:24 2016"print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))
The output of the above example :
2016-04-07 10:25:09Thu Apr 07 10:25:09 20161459175064.0
Get the calendar of a month
Calendar Module has a wide range of methods to deal with calendar and calendar , For example, printing the calendar of a month :
#!/usr/bin/python# -*- coding: UTF-8 -*-import calendar
cal = calendar.month(2016, 1)print " The following output 2016 year 1 Calendar of the month :"print cal;
The output of the above example :
The following output 2016 year 1 Calendar of the month :
January 2016Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 1011 12 13 14 15 16 1718 19 20 21 22 23 2425 26 27 28 29 30 31
more Python Course : Alibaba cloud University —— Developer class