time模块
graph LR A[Timestamp] -->|localtime/gmtime| B[struct time] B -->|strftime| C[format time] graph LR A[format time] -->|strptime| B[struct time] B -->|mktime| C[Timestamp]-
time.time()
返回当前时间的Timestamp>>> time.time() 1627972273.3945653
-
time.localtime([second=None])
将一个Timestamp转换为当前时区的struct time, 默认为当前时区时间的Timestamp>>> time.localtime() time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=14, tm_min=32, tm_sec=20, tm_wday=1, tm_yday=215, tm_isdst=0)
-
time.gmtime([second=None])
将一个Timestamp转换为UTC时区(格林威治时间, 0时区)的struct time, 默认为当前时区时间的Timestamp>>> time.gmtime() time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=6, tm_min=33, tm_sec=29, tm_wday=1, tm_yday=215, tm_isdst=0)
-
time.strftime(format, p_tuple=None)
根据格式规范, 将一个时间的元祖或struct time转换为时间字符串, 默认为当前时区时间的struct time格式化时间代码:
%Y 年
%m 月
%d 日
%H 小时(24小时制)
%M 分钟
%S 秒数
%z 与UTC的时区偏差
%a 星期缩写
%A 星期全拼
%b 月份缩写
%B 月份全拼
%c 日期时间
%I 小时(12小时制)
%p AM or PM>>> time.strftime("%Y-%m-%d %H:%M:%S") '2021-08-03 14:36:38' >>> time.strftime("%z") '+0800' >>> time.strftime("%a %A %b %B") 'Tue Tuesday Aug August' >>> time.strftime("%c") 'Tue Aug 3 14:38:20 2021' >>> time.strftime("%I %p") '02 PM'
-
time.asctime(p_tuple=None)
将一个时间元祖或struct time转换为格式为"Sat Jun 06 16:26:11 1998"的字符串, 默认为当前时区时间的struct time>>> time.asctime() 'Tue Aug 3 14:59:22 2021'
time.asctime()
相当于time.strftime(%c)
-
time.strptime(string, format)
根据格式规范, 将一个时间字符串转换为一个时间元祖>>> time.strptime("Tue Aug 3 14:38:20 2021") time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=14, tm_min=38, tm_sec=20, tm_wday=1, tm_yday=215, tm_isdst=-1) >>> time.strptime("2021-08-03 14:36:38", "%Y-%m-%d %H:%M:%S") time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=14, tm_min=36, tm_sec=38, tm_wday=1, tm_yday=215, tm_isdst=-1)
-
time.mktime(p_tuple)
将当前时区时间的struct time转换为一个Timestamp>>> time.mktime(time.localtime()) 1627973508.0
-
time.sleep(seconds)
延迟执行一个给定的秒数