2016-02-23 22 views
0

在做一件非常基本的事情時,網上似乎有很多混淆:創建一個UTC時區的datetime對象,在UTC時區的unix時代以後給定秒數。基本上,我總是希望在絕對時間/ UTC工作。如何創建自UNIX時代以來秒數的日期時間對象?

我使用python 3.5(目前最新的),並希望簡單地得到一個datetime對象UTC(+ 0 /祖魯偏移)從經過秒浮點值,因爲1970年01月的

上下文

這是錯誤的,因爲第一次在我的本地時區中創建,然後我嘗試切換到UTC。

import datetime 
import pytz 
dt = datetime.datetime.fromtimestamp(my_seconds).replace(tzinfo=pytz.UTC) 

回答

3

Python爲此提供了方法utcfromtimestamputcfromtimestamp

import datetime 

seconds = 0 
utcdate_from_timestamp = datetime.datetime.utcfromtimestamp(seconds) 
0

如果my_seconds是POSIX時間戳,然後將其轉換爲datetime在Python 3:

#!/usr/bin/env python3 
from datetime import datetime, timedelta, timezone 

utc_dt = datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=my_seconds) 
utc_dt = datetime.fromtimestamp(my_seconds, timezone.utc) 
naive_utc_dt = datetime.utcfromtimestamp(my_seconds) 

如果您的本地時區是「正確的」(非POSIX),那麼只有第一個公式正確(其他人將my_seconds解釋爲TAI時間戳,在此情況下用datetime(1970, 1, 1, 0, 0, 10) TAI時期解釋)。

The first formula is more portable and may support a wider input range than the others.

的第一和第二表現形式的結果可能不同,由於rounding errors on some Python versions

第二次和第三次調用只應該有區別tzinfo attibute(後者返回一個天真的日期時間對象(.tzinfo is None))。您應該更喜歡時區感知的日期時間對象,以避免含糊不清。

相關問題