time module
1. Get the current timestamp.
The number of seconds from January 1, 1970, 0:0:0:0 in time zone 0, to the given date-time, as a floating-point number.
import time
print (time.time ())
1523587843.3224387
2. Get the time ancestor.
Many python time functions treat time as a tuple of 9 numbers, as shown below
time.localtime([seconds]), the default current timestamp.
>>> import time
>>> time.localtime()
time.struct_time(tm_year=2018, tm_mon=4, tm_mday=13,tm_hour=10, tm_min=59, tm_sec=54, tm_wday=4, tm_yday=103, tm_isdst=0)
3. Get the formatting time.
3.1 seconds -> readable
import time
time.ctime([seconds]), optional timestamp, default current timestamp
>>>import time
>>>time.ctime()
'FriApr 13 10:57:06 2018'
3.2 time tuple -> readable time
import time
time.asctime([p_tuple]), optional time tuple, default current time tuple
>>> importtime
>>>time.asctime()
'Fri Apr 13 11: 01: 592018'
4. Format date string <--> timestamp
4.1 Time tuple -> formatted date
time.strftime(format string, time tuple)
>>>time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
'2018-04-1311:05:47'
4.2 Formatting date->time tuples
time.strptime(date string, format string)
time.mktime(time tuple)
>>>time.mktime(time.strptime("2017-09-02 17:21:00", "%Y-%m-%d%H:%M:%S"))
1504344060.0
>>>time.strptime("2017-09-02 17:21:00", "%Y-%m-%d %H:%M:%S")
time.struct_time(tm_year=2017,tm_mon=9, tm_mday=2, tm_hour=17, tm_min=21, tm_sec=0, tm_wday=5, tm_yday=245,tm_isdst=-1)
5. Get the current cpu time
time.clock( ), a floating-point number, can be used to count the execution time of a piece of program code
6. Sleep n seconds
Postponing the execution of threads can be simply understood as letting the program suspend
time.sleep(secs)
calendar module
Get a month's calendar
import calendar print(calendar.month(2018,4))
datetime module
There are datetime classes in this module, and date classes and time classes are also commonly used.
1. Get today's date
>>> import datetime
>>>datetime.datetime.now()
datetime.datetime(2018, 4,13, 11, 18, 33, 996080)
>>>datetime.datetime.today()
datetime.datetime(2018, 4,13, 11, 18, 51, 252080)
2. Get the current year, month, day, hour, minute and second separately
year,month,day,hour,minute,second
>>> import datetime
>>>datetime.datetime.now().year
2018
3. Calculate the time after n days
>>> import datetime
>>>datetime.datetime.now()+datetime.timedelta(days = 7)
datetime.datetime(2018, 4,20, 11, 28, 53, 688080)
4. Obtain two time differences
5、 import datetime first = datetime.datetime(2018,4,15,00,00,00) second = datetime.datetime(2018,4,18,00,00,00) result = second -first print(result.total_seconds())