[英]How to convert a localized timestamp to UTC using Python?
我需要將任意時區中的“本地化”時間戳轉換為 unix 時間戳(以 UTC 為單位)。
>>> import pytz
# This represents 2019-09-11T16:14:00 (US/Central) or 2019-09-11T21:14:00 UTC!
>>> local_timestamp = 1568218440
>>> tz = pytz.timezone("US/Central")
>>> my_unix_timestamp = unix_timestamp(local_timestamp, tz)
>>> print(my_unix_timestamp)
1568236440 # 2019-09-11T21:14:00
我知道這已經被問過很多次了,但是我對從任意時區進行時間戳的初始轉換感到困惑,因為在構造初始datetime
時間 object 時必須明確設置tz
(如我的回答中所述)。
時間戳(POSIX)永遠不應該被本地化; 它應始終指 UTC。 否則,這可能會因模棱兩可而導致嚴重的頭痛。 只有datetime
時間 object 應該本地化(tz-aware),即包含時區信息(tzinfo.= None):示例:
from datetime import datetime, timezone
import dateutil
datetime.fromisoformat('2019-09-11T21:14:00').replace(tzinfo=timezone.utc).timestamp()
# 1568236440.0
datetime.fromisoformat('2019-09-11T16:14:00').replace(tzinfo=dateutil.tz.gettz("US/Central")).timestamp()
# 1568236440.0
旁注: pytz
使用與datetime
模塊(Python 標准庫)不同的時區 model。 這就是為什么您不能安全地使用日期時間 object 的replace
方法來設置時區的原因。 如果您想讓您的生活更輕松,請查看dateutil
。 您可以在這里安全地使用replace
。
還要小心天真的日期時間對象。 Python 默認將它們視為本地時間,請參見例如this answer 。
如pytz
文檔中所述,標准 Python datetime.replace()
方法沒有正確考慮夏令時。 您應該使用 pytz 的timezone.localize()
方法。
另一個問題是,在從輸入時間戳創建datetime
時間 object 時,您必須明確定義tz
信息。 否則,假定您的時間戳是本地(系統)時間。 正如datetime
文檔中所述,出於這個原因,您應該避免使用datetime.utcfromtimestamp()
。
所以:
from datetime import datetime, timezone
def unix_timestamp(local_timestamp, local_timezone):
"""turn the input timestamp into a UTC `datetime` object, even though
the timestamp is not in UTC time, we must do this to construct a datetime
object with the proper date/time values"""
dt_fake_utc = datetime.fromtimestamp(local_timestamp, tz=timezone.utc)
"""remove the (incorrect) timezone info that we supplied """
dt_naive = dt_fake_utc.replace(tzinfo=None)
"""localize the datetime object to our `timezone`. You cannot use
datetime.replace() here, because it does not account for daylight savings
time"""
dt_local = local_timezone.localize(dt_naive)
"""Convert our datetime object back to a timestamp"""
return int(dt_local.timestamp())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.