正如你可以從下面的代碼片段看到的,兩種方法之間有一個小時的差異。是什麼原因 ?爲什麼datetime.utcnow()和datetime.now(timezone('UTC'))之間有區別?
from datetime import datetime
from pytz import timezone
import time
def timestamp2date(timestamp):
# function converts a UTC timestamp into Europe/Zurich Gregorian date
DATE_TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
utcTimeStamp = datetime.fromtimestamp(int(timestamp)).replace(tzinfo=timezone('UTC'))
return utcTimeStamp.astimezone(timezone('Europe/Zurich')).strftime(DATE_TIME_FORMAT)
timeStampUTC_1 = time.mktime(datetime.utcnow().timetuple())
print(timeStampUTC_1)
print(timestamp2date(timeStampUTC_1))
timeStampUTC_2 = time.mktime(datetime.now(timezone('UTC')).timetuple())
print(timeStampUTC_2)
print(timestamp2date(timeStampUTC_2))
print(timeStampUTC_2 - timeStampUTC_1)
# 1504385450.0
# 2017-09-03 00:50:50 this the right time
# 1504389050.0
# 2017-09-03 01:50:50
# 3600.0
我沒有在我的Windows 10筆記本電腦QPython NND我的Android智能手機,其執行的Python 3.2解釋器中運行的python 3.6的代碼,我獲得同樣的區別。我當地的時區是歐洲/蘇黎世。 –
...但即使以美國/太平洋作爲時區,差異也是如此。 –