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表格的網站