There are three ways to represent time in python:
- Timestamp: Generally speaking, a timestamp represents an offset in seconds from January 1, 1970 00:00:00. The returned type is flot. The functions that generate timestamps mainly include time(), clock() and so on.
- Formatted time string (Format String)
- Structured time (struct_time): The struct_time tuple has nine elements in total: (year, month, day, hour, minute, second, week of the year, day of the year, daylight saving time) . The methods that return struct_time are gmtime(), localtime(), strptime()
Let's take a look at the common methods of the time module:
import time # time() returns a timestamp of the current time print (time.time()) # 1525509143.3561425 (this is a timestamp) # localtime() converts a timestamp to a struct_time() in the current region, not set The default is the current time print (time.localtime(1525509143.3561425 )) # time.struct_time(tm_year=2018, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=32, tm_sec=23, tm_wday=5, tm_yday=125, tm_isdst=0) # gmtime() is similar to localtime, but returns UTC. print (time.gmtime(1525509143.3561425 )) # time.struct_time(tm_year=2018, tm_mon=5, tm_mday=5, tm_hour=8, tm_min=32, tm_sec=23, tm_wday=5, tm_yday=125, tm_isdst=0) # mktime converts a strut_time into a timestamp print (time.mktime(time.localtime())) # 1525509143.3561425 # The first time clock() returns is the running time of the program, and the second is the direct time difference with the first clock. import time print (time.clock()) # 4.72616147781398e-07 This number is basically equal to 0 time.sleep(2 ) print (time.clock()) # 1.9999187100225817 is equal to 2 # time.asctime([t]): Express a tuple or struct_time representing time in this form: 'Sun Jun 20 23:21:05 1993'. If there are no arguments, time.localtime() will be passed in as an argument. print(time.asctime()) #Sat May 5 16:52:07 2018 # time.ctime([secs]): Convert a timestamp (floating point number in seconds) to the form of time.asctime(). The default parameter is time.time() print(time.ctime()) #Sat May 5 16:54:30 2018 # time.strftime(format[, t]): Convert a tuple or struct_time representing time into a formatted time string. If t is not specified, it will be passed to time.localtime(). Commonly used formatting control characters are, %Y year %m month %d day %X local time %x local date % M minutes print (time.strftime( " % x %X " ,time.localtime())) # 05/05/18 17:03:02 print (time.strftime( " %Y %m %d %X " ,time.localtime())) # 2018 05 05 17:04:49