最近在開發 Auth Module 的時候有用到 Unix Timestamp 來做驗證,原先我的開發環境都是在 Container 下所以時區都是 UTC+0
不過自己寫的小工具是在 UTC+8 的環境開發,於是乎學習到了 Python 的 bug (feature)…
原先我的 testing tool 是使用以下程式碼來取得 Unix Timestamp
1 2 |
from datetime import datetime datetime.utcnow().timestamp() |
但我發現這樣 Server 總是回我 Client 與自己的時間相差過大 (??
看到錯誤訊息我馬上去檢查是不是我的 local environment 時間沒有校對,檢查校對後重新再試一次又得到了同樣的錯誤訊息
接着我想說死馬當活馬醫乾脆用一般的方式拿 Unix Timestamp 試試看好了程式碼如下
1 2 |
from datetime import datetime datetime.now().timestamp() |
竟然 pass 了!!!
到底花生神魔術,馬上拿關鍵字去餵狗得到一篇 Using datetime.datetime.utcnow().timestamp() in Python3.6.0 can’t get correct UTC timestamp.
大意是說 datetime.utcnow()
的 tzinfo = None
所以呼叫 timestamp()
的時候會幫你做減去當前時區再取得 Timestamp 的動作,而這樣的行爲會造成無法取得預期 Unix Timestamp,原來…這不是 bug 這是 feature …
嗯好… 總結一下取得 Unix Timestamp 的方法有兩種:
time.time()
datetime.now().timestamp()