【问题标题】:Why does Convertingt EST datetime object to UTC unix timestamp and back to EST add 5 hours?为什么将 EST 日期时间对象转换为 UTC unix 时间戳并返回 EST 会增加 5 小时?
【发布时间】:2018-05-11 06:42:37
【问题描述】:

为什么在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>)

【问题讨论】:

    标签: python datetime timezone pytz


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-24
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 2021-11-15
      • 1970-01-01
      • 2020-12-01
      相关资源
      最近更新 更多