| From | To | Use |
|---|---|---|
| seconds since the epoch | struct_time in UTC | gmtime() |
| seconds since the epoch | struct_time in local time | localtime() |
| struct_time in UTC | seconds since the epoch | calendar.timegm() |
| struct_time in local time | seconds since the epoch | mktime() |
表格来自time — Time access and conversions,注意时间戳也就是秒是不分时区的。
假设现在有时间戳0秒,当将该时间分别转为UTC时间或本地时间时,转换如下:
from time import gmtime, localtime, strftime
sec = 0
# 获取时间元组
utctime = gmtime(sec)
localtime = localtime(sec)
print('若转为UTC时间:',
strftime('%Y/%m/%d %H:%M:%S', utctime))
print('若转为当地时间:',
strftime('%Y/%m/%d %H:%M:%S', localtime))
输出:
若转为UTC时间: 1970/01/01 00:00:00
若转为当地时间: 1970/01/01 08:00:00
显而易见,gmtime会将时间戳转为UTC时间,localtime()会将时间戳转为当地时间。
假设现在有时间’1970/01/01 08:00:00’,当该时间分别为UTC时间或本地时间时,转换如下:
from calendar import timegm
from time import strptime, mktime
strtime = '1970/01/01 08:00:00'
tuptime = strptime(strtime, '%Y/%m/%d %H:%M:%S')
print('若给出的是UTC时间:', timegm(tuptime))
print('若给出的是当地时间:', mktime(tuptime))
输出:
若给出的是UTC时间: 28800
若给出的是当地时间: 0.0
显而易见,timegm认为你给出的是UTC,mktime认为你给出的是当地时间。
补充:GMT->gm
表格中的时间结构体,就是我们通常所说的时间元组
程序中为了看起来方便,对时间元组做了相应的转化
附加一个自动生成markdown表格的网站
本文深入探讨了时间戳的概念,以及如何使用Python中的gmtime(), localtime(), timegm(), 和 mktime()函数进行时间戳与UTC时间及本地时间的相互转换。通过具体示例,展示了不同时间转换函数的应用场景。
1250

被折叠的 条评论
为什么被折叠?



