为什么 Convertingt EST datetime 反对 UTC unix 时间戳并返回 EST 增加 5 小时?

Why does Convertingt EST datetime object to UTC unix timestamp and back to EST add 5 hours?

为什么在 dt 上调用以下 2 个函数会导致增加 5 个小时?我以为它会保持不变。

from datetime import datetime, time, timedelta
from pytz import timezone

def est_datetime_to_utc_timestamp(dt):
    dt_utc = dt.astimezone(timezone('UTC'))
    ts = int(dt_utc.strftime("%s"))
    return ts

def utc_timestamp_to_est_datetime(ts):
    dt = datetime.fromtimestamp(ts, timezone('UTC'))
    dt = dt.astimezone(timezone('America/New_York'))
    return dt

dt = timezone('America/New_York').localize(datetime(2017, 11, 27, 0, 0))

utc_timestamp_to_est_datetime(est_datetime_to_utc_timestamp(dt))

> datetime.datetime(2017, 11, 27, 5, 0, tzinfo=<DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>)

strftime("%s") 并非在每个实现中都定义。

将其替换为 .timestamp() 适用于 Python 3.3+,并给出正确的结果。

或者,如果不在 Python 3.3+ 上,您可以使用 (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()