python中时间戳与时间字符的相互转换

2023-12-13 04:08:22

1.获取时间的方法

使用的是time模块

import time
time1 = time.time()
# time1: 1701934920.676534
timestruct = time.localtime(time1)
# timestruct: time.struct_time(tm_year=2023, tm_mon=12, tm_mday=7, tm_hour=15, tm_min=42, tm_sec=0, tm_wday=3, tm_yday=341, tm_isdst=0)

2.将时间戳转化为标识时间的字符串

timestr =time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time1))
# timestr: '2023-12-07 15:42:00'

3.将字符串转化为时间戳

dateTime = time.strptime("2023-12-07 15:42:00","%Y-%m-%d %H:%M:%S")
# dateTime: time.struct_time(tm_year=2023, tm_mon=12, tm_mday=7, tm_hour=15, tm_min=42, tm_sec=0, tm_wday=3, tm_yday=341, tm_isdst=-1)
secondsFrom1970=time.mktime(dateTime)
# secondsFrom1970: 1701934920.0

时间结构体的时间型式参考文章Python time模块 strftime() 和time.localtime()方法icon-default.png?t=N7T8https://blog.csdn.net/qq727923587/article/details/117708106?spm=1001.2014.3001.5506

文章来源:https://blog.csdn.net/w1015601709/article/details/134857189
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。