【问题标题】:Cannot convert timestamp to date in Python with correct timezone无法在 Python 中使用正确的时区将时间戳转换为日期
【发布时间】:2022-01-17 07:06:42
【问题描述】:

我有一个如下所示的 Pandas DataFrame:

timestamp
1583985600000
1584072000000
1584331200000
1584417600000
1584504000000
1584590400000

实际上还有其他列,但为了简单起见,我粘贴了上面的列。

我需要通过在同一个 DataFrame 中创建一个单独的列来将此列更改为日期格式。我尝试以下方法:

df["date EST"] = pd.to_datetime(agg_daily_df["timestamp"],
                    unit='ms').dt.tz_localize('EST').astype(str)

... 给出以下结果:

date EST
2020-03-12 04:00:00-05:00
2020-03-13 04:00:00-05:00
2020-03-16 04:00:00-05:00
2020-03-17 04:00:00-05:00
2020-03-18 04:00:00-05:00
2020-03-19 04:00:00-05:00

...这对我来说看起来很奇怪。第一行实际上应该给 2020-03-12 00:00:00.

我在这里做错了什么,所以我得到了一种奇怪格式的结果?

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    这将返回 UTC 时间作为 tz-naive datetime。

    pd.to_datetime(agg_daily_df["timestamp"], unit='ms')
    
    # 1583985600000 => 2020-03-12 04:00:00
    

    所以,本地化这个日期时间,结果是

    original:       1583985600000 => 
    pd.to_datetime: 2020-03-12 04:00:00 (tz-naive) => 
    tz_localize:    2020-03-12 04:00:00-05:00 (tz-aware, EST)
    

    问题是在转换到其他时区之前,您需要具有 tz 感知日期时间。

    # Add utc=True to get tz-aware time and convert to EST
    (pd.to_datetime(agg_daily_df["timestamp"], unit='ms', utc=True)
       dt.tz_convert('EST'))
    

    这样时间会这样转换。

    original:                  1583985600000 => 
    to_datetime with utc=True: 2020-03-12 04:00:00+00:00 (tz-aware, UTC) => 
    tz_convert:                2020-03-11 23:00:00-05:00 (tz-aware, EST)
    

    请注意,“EST”时区不处理夏令时。如果您想进行夏令时处理,请使用 locale 作为时区。

    (pd.to_datetime(agg_daily_df["timestamp"], unit='ms', utc=True)
       .dt.tz_convert('America/New_York'))
    

    这会给你2020-03-12 00:00:00-04:00

    ================================================ =========

    更新:

    如果您想再次体验 tz-naive,请通过 tz_localize(None) 删除 tzinfo

     (pd.to_datetime(agg_daily_df["timestamp"], unit='ms', utc=True)
       .dt.tz_convert('America/New_York')
       .tz_localize(None))
    

    或者,如果您只想有时间而不显示时区偏移,请使用strftime 将日期时间格式化为字符串。

    (pd.to_datetime(agg_daily_df["timestamp"], unit='ms', utc=True)
       .dt.tz_convert('America/New_York')
       .transform(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'))
    

    【讨论】:

    • 非常感谢您的详细解释!但是结果的格式应该是 2020-03-12 00:00:00 而不是 2020-03-12 00:00:00-04:00。我如何实现这一目标?此外,日光节约也很重要。我想将时间戳转换为 EST 中的本地时间。我如何通过考虑夏令时来实现这一目标?
    • 您想要拥有 tz-naive 日期时间对象还是只是没有时区偏移的格式?对于夏令时的处理,我已经在答案中指出(“注意...”的最后一部分)。
    • 现在一切都清楚了。非常感谢您花时间给出如此详细的解释。
    猜你喜欢
    • 2022-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    相关资源
    最近更新 更多