【问题标题】:Converting timezones from pandas Timestamps从熊猫时间戳转换时区
【发布时间】:2014-10-28 11:56:46
【问题描述】:

我在数据框中有以下内容:

> df['timestamps'].loc[0]
Timestamp('2014-09-02 20:24:00')

我知道它使用的时区(我认为是GMT),并希望将整个列转换为EST。如何在 Pandas 中做到这一点?

作为参考,我发现了这些其他线程:

但它们使用datetime 时间戳。例如:

> datetime.datetime.fromtimestamp(df['timestamps'].loc[0], tz=None)
returns:

TypeError                                 Traceback (most recent call last)
----> 2 datetime.datetime.fromtimestamp(ts, tz=None)

TypeError: an integer is required (got type Timestamp)

【问题讨论】:

    标签: python pandas timezone


    【解决方案1】:

    只需使用tz_convert 方法。

    假设你有一个 Timestamp 对象:

       stamp = Timestamp('1/1/2014 16:20', tz='America/Sao_Paulo')
       new_stamp = stamp.tz_convert('US/Eastern')
    

    如果您有兴趣转换日期范围:

       range = date_range('1/1/2014', '1/1/2015', freq='S', tz='America/Sao_Paulo')
       new_range = range.tz_convert('US/Eastern')
    

    对于大时间序列:

       import numpy as np
       ts = Series(np.random.randn(len(range)), range)
       new_ts = ts.tz_convert('US/Eastern')
    

    如另一个答案所述,如果您的数据没有设置时区,您需要tz_localize它:

       data.tz_localize('utc')
    

    【讨论】:

    • 谢谢,但是当我尝试时:df['timestamps'][0].tz_convert('US/Eastern') 我得到:Exception: Cannot convert tz-naive Timestamp, use tz_localize or localize
    • 如果我尝试直接使用该列,则相同:df['timestamps'].tz_convert('US/Eastern')TypeError: index is not a valid DatetimeIndex or PeriodIndex
    • 是的。非常感谢@rhlobo
    • 注意:您不能直接在上使用tz_localizetz_convert,只能在索引上使用
    【解决方案2】:

    日期时间的 fromtimestamp 实际上来自 POSIX 时间戳,即 1970-1-1 GMT 的毫秒数

    In [11]: datetime.datetime.fromtimestamp?
    Type:        builtin_function_or_method
    String form: <built-in method fromtimestamp of type object at 0x101d90500>
    Docstring:   timestamp[, tz] -> tz's local time from POSIX timestamp.
    
    In [12]: datetime.datetime.fromtimestamp(0)
    Out[12]: datetime.datetime(1969, 12, 31, 16, 0)
    
    In [13]: datetime.datetime.fromtimestamp(1)
    Out[13]: datetime.datetime(1969, 12, 31, 16, 0, 1)
    

    我认为这可能是一个问题,因为我在 PST 时区。

    这与 pandas 时间戳不同(尽管在 ns 从 1970-1-1 开始)。

    In [21]: pd.Timestamp(0)
    Out[21]: Timestamp('1970-01-01 00:00:00')
    

    要转换 Timestamp/datetime64 列,请使用 tz_convert(如果 tz 天真,即还没有时区,则需要先进行 tz_localize):

    In [31]: pd.Timestamp(0).tz_localize('UTC')
    Out[31]: Timestamp('1970-01-01 00:00:00+0000', tz='UTC')
    
    In [32]: t = pd.Timestamp(0).tz_localize('UTC')
    
    In [33]: t.tz_convert('US/Eastern')
    Out[33]: Timestamp('1969-12-31 19:00:00-0500', tz='US/Eastern')
    

    time-zone-handling section of the docs

    【讨论】:

      【解决方案3】:

      如何将 UTC 时间(最初从 Unix 时间)转换为美国/东部时间的示例。

      这在矢量化模式下运行,因此速度非常快:数百万行在几秒钟内运行。

      在 Python 3.9 上测试。

      df = pd.DataFrame({"timestamp": [Timestamp("2017-01-03 14:30:00.049"), Timestamp("2017-01-03 14:30:00.049"), Timestamp("2017-01-03 14:30:00.049")],
                         "x": [1,2,3]})
      timestamp = df["timestamp"].values
      timestamp = pd.to_datetime(timestamp)
      timestamp = timestamp.tz_localize("UTC").tz_convert("US/Eastern") # Convert UTC to US/Eastern
      timestamp = timestamp.tz_localize(None)  # Strip timezone information off.
      df["timestamp"] = timestamp.values
      df
      

      在:

                    timestamp  x
      2017-01-03 14:30:00.049  1
      2017-01-03 14:30:00.049  2
      2017-01-03 14:30:00.049  3
      

      输出:

                    timestamp  x
      2017-01-03 09:30:00.049  1
      2017-01-03 09:30:00.049  2
      2017-01-03 09:30:00.049  3
      

      奖金

      如果该列最初是 Unix 时间(毫秒),则使用它来将其转换为 datetime64[ns] 数组:

      timestamp = pd.to_datetime(timestamp, unit="ms")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-21
        • 2020-04-16
        • 1970-01-01
        • 2016-03-27
        • 1970-01-01
        • 2014-05-19
        • 1970-01-01
        • 2018-10-23
        相关资源
        最近更新 更多