Python Provides a time Module to format the time , stay python Very useful in applications such as crawlers .
time The module contains information for obtaining the current time 、 Operation time and date 、 Read date from string 、 Format the date as a string function . The date can be expressed as since 1970 year 1 month 1 Midnight ( Epoch ) A real number after seconds , It can also be expressed as including 9 A tuple of integers .
import time
ticks = time.time()
print (" The current timestamp is :", ticks)
The current timestamp is : 1645263377.554756
The above case demonstrates the use of time()
Get the current timestamp .
quite a lot Python Functions are assembled in one element 9 Group digital processing time :
The value range of seconds is 0~61, Consider the leap of one or two seconds . Daylight saving time numbers are Boolean , If you use -1, Indicates unknown , So use mktime() You may get the correct value .
import time
localtime = time.localtime()
print (" The local time is :", localtime)
The local time is : time.struct_time(tm_year=2022, tm_mon=2, tm_mday=19, tm_hour=17, tm_min=49, tm_sec=21, tm_wday=5, tm_yday=50, tm_isdst=0)
The above example demonstrates how to get the time tuple of the current time .
localtime()
The default value is time()
The current timestamp returned .
You can choose various formats according to your needs , But the simplest function to get a readable time pattern is asctime():
import time
localtime = time.asctime(time.localtime())
print (" The local time is :", localtime)
The local time is : Sat Feb 19 17:59:17 2022
It can also be used directly here asctime()
, because asctime()
The default value is localtime()
Current time returned .
Can also be used ctime()
, ctime()
Equivalent to asctime(localtime())
.
We can use time Modular strftime Method to format the date :time.strftime(format[, t])
, The first parameter is the format string , The second parameter is the time tuple .
import time
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
2022-02-19 18:28:08
Sat Feb 19 18:28:08 2022
The above example demonstrates how to format the local time .
asctime([t])
Convert time tuples to strings ctime([secs])
Convert seconds to strings localtime([secs])
Convert seconds to time tuples of local time gmtime([secs])
Convert seconds to UTC Time tuple of time mktime(t)
Convert time tuples to local time sleep(secs)
Sleep secs second strftime(format[, t])
Convert string to time tuple time()
current time , Seconds since the era Official documents :https://docs.python.org/zh-cn/3/library/time.html