After introducing the background of the computer time, I will give you a summary of the examples that are commonly used to get the system time using python, so that you can get started and query quickly, and supports common date formats. Let's first talk about how to use the time module to time the time we need:
>>> Import time
>>> Time. time ()
1469101837.655935
The time. time () function is the returned UTC time, which is the number of seconds from 1970.1.1 to the present.
>>> Time. ctime (1469101837.655935)
'Thu Jul 21 19:50:37 123'
The time. ctime () function receives an actual value in seconds and then converts the string representation of the local time.
If we want to format the output of the time format, we can use the strftime () function to convert our time format into the desired format:
>>> From time import strftime, gmtime
>>> Strftime ("% m/% d/% Y % H: % M ")
'2014/1/0'
>>> Time. strftime ("% Y % m % d ")
'123'
>>> Strftime ("% Y-% m-% d % H: % M: % S", gmtime ())
'2017-07-21 11:47:51'
In python, apart from the time module, the datetime module can also be used for convenient time operations. For example, the datetime module can be used to display the current time:
>>> From datetime import datetime
>>> Datetime. now (). strftime ('% Y-% m-% d % H: % M: % S ')
'2017-07-21 19:49:15'
>>> Datetime. now (). isoformat ()
'2017-07-21T19: 56: 8080'
>>> Str (datetime. now ())
'2017-07-21 19:48:37. 123'
Unix timestamp: the number of seconds elapsed since midnight on January 1, January 1, 1970 (UTC/GMT). Skip the leap second.
Import datetime
Import time
Print time. mktime (datetime. datetime. now (). timetuple ())
Output:
1431674373.0
These two modules are commonly used in scripts, such as the timestamp variable to be added during file backup and the time variable to delete old files, you can use the preceding example to modify the desired format. If you only need a certain part of the time, you can use the split () function to split it and obtain the desired content through slicing, this article is here. If you have any questions, please leave a message.