转自:https://www.pinlue.com/article/2021/07/2700/0011651539200.html
-
time.sleep(secs) #推迟指定的时间(secs)后继续运行
-
time.localtime([secs]) #将一个时间戳转换成一个当前时区的struct_time,如果seconds参数未输入,则以当前时间为转换标准
未提供secs参数时,按当前时间为准
-
time.strftime(format[, t]) #将指定的struct_time(默认为当前时间),根据指定的格式化字符串输出
-
time.time() #返回当前时间的时间戳
-
time.mktime(t) #将一个struct_time转换为时间戳,如下time.localtime接收一个时间戳返回一个struct_time,而time.mktime接收一个struct_time,返回一个时间戳
-
time.gmtime([secs]) #和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time
-
time.clock() #这个需要注意,在不同的系统上含义不同。 在UNIX系统上,它返回的是“进程时间”,它是用秒表示的浮点数(时间戳)。而在WINDOWS中,第一次调用,返回的是进程运行的实际时间。而第二次 之后的调用是自第一次调用以后到现在的运行时间。(实际上是以WIN32上QueryPerformanceCounter()为基础,它比毫秒表示更为 精确)
-
time.asctime([t]) #把一个表示时间的元组或者struct_time表示为这种形式:‘Sun Jun 20 23:21:05 1993’。如果没有参数,将会将time.localtime()作为参数传入
-
time.ctime([secs]):把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果参数未给或者为None的时候,将会默认time.time()为参数。它的作用相当于time.asctime(time.localtime(secs))
-
time.strftime(format[, t]) #把一个代表时间的元组或者struct_time(如由time.localtime()和time.gmtime()返回)转化为格式化的时间字符串。 如果t未指定,将传入time.localtime()。如果元组中任何一个元素越界,ValueError的错误将会被抛出
代码实例:
import time
使用time模块,首先得到当前的时间戳
time.time()
1513855961.782587
将时间戳转换为时间元组 struct_time
time.localtime(time.time())
time.struct_time(tm_year=2017, tm_mon=12, tm_mday=21, tm_hour=19, tm_min=33, tm_sec=17, tm_wday=3, tm_yday=355, tm_isdst=0)
格式化输出想要的时间
time.strftime(’%Y-%m-%d %H:%M:%S’,time.localtime(time.time()))
‘2017-12-21 19:33:40’
接上文,不加参数时,默认就是输出当前的时间
time.strftime(’%Y-%m-%d %H:%M:%S’)
‘2017-12-21 19:33:53’
使用的时候需要注意一下使用的时区。
datetime
datetime 比 time 高级了不少,可以理解为 datetime 基于 time 进行了封装,提供了更多实用的函数。在datetime 模块中包含了几个类,具体如下:
timedelta # 主要用于计算时间跨度
tzinfo # 时区相关
time # 只关注时间
date # 只关注日期
datetime # 同时有时间和日期
在实际实用中,用得比较多的是 datetime.datetime 和 datetime.timedelta ,另外两个 datetime.date 和 datetime.time 实际使用和 datetime.datetime 并无太大差别。 对于一个 datetime.datetime 实例,主要会有以下属性及常用方法:
datetime.year
datetime.month
datetime.day
datetime.hour
datetime.minute
datetime.second
datetime.microsecond
datetime.tzinfo #时区
datetime.date() # 返回 date 对象
datetime.time() # 返回 time 对象
datetime.replace(name=value) # 前面所述各项属性是 read-only 的,需要此方法才可更改
datetime.timetuple() # 返回time.struct_time 对象
dattime.strftime(format) # 按照 format 进行格式化输出