簡體   English   中英

Python3 中的紀元日期轉換未按預期工作

[英]Epoch date conversion in Python3 not working as expected

我正在使用一個以“1619714600948”格式存儲時間的應用程序,該格式有 13 個字符長。 我相信這是一個划時代的日期。 使用站點https://www.epochconverter.com/證實了這一點。 我可以輸入 13 個字符的日期並退出:

在此處輸入圖像描述

當我嘗試在 Python3 中創建一個紀元日期時,我最終得到 1619703857,它只有 10 個字符長。 當我嘗試比較存儲的日期與生成的日期時,這會導致問題。 為什么我沒有得到預期的 13 個字符的紀元日期? 以下是我根據搜索 Stackoverflow 嘗試過的一些事情

date_time2 = '04.29.2021' + " " + "13:44:17.000000"
pattern2 = '%m.%d.%Y %H:%M:%S.%f'

# get a time structure
tm = time.strptime(date_time2, pattern2)

# convert to gmt
gmt_epoch = int(calendar.timegm(tm))
print(gmt_epoch) #10 digit result 


date_string = calendar.timegm(time.strptime(str(date.today()), '%Y-%m-%d'))
print(date_string) #10 digit result 

嘗試從中轉換給我的日期有 5 位數的年份。

print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1619714600948))) #Bogus date of 53296-09-16 11:29:08
print(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(1619714600948))) # Bogus date of 53296-09-16 18:29:08

是什么導致了這種差異,我該如何解決?

這是一個以毫秒為單位的 UNIX 時間(在 JavaScript 中很常見)。 除以 1000。

>>> import datetime
>>> datetime.datetime.fromtimestamp(1619714600948 / 1000.)
datetime.datetime(2021, 4, 29, 19, 43, 20, 948000)

同樣,乘以 1000 得到毫秒時間戳:

>>> datetime.datetime.now().timestamp() * 1000
1619718337164.896

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM