【问题标题】:Convert Pandas DF with timestamp string to local datetime without tz将带有时间戳字符串的 Pandas DF 转换为不带 tz 的本地日期时间
【发布时间】:2019-11-22 01:56:16
【问题描述】:

我有带有字符串时间戳的 DataFrame 列,我想将其转换为没有时区的本地日期时间。

df = {'id' : [1, 2, 3],
      'timestamp' : ['2019-07-01T21:30:20Z', '2019-07-02T21:30:20Z', '2019-07-03T21:30:20Z']}
df = pd.DataFrame(df, columns = ['id','timestamp'])

我的代码:

df['timestamp'] = (pd.DatetimeIndex(pd.to_datetime(df['timestamp'], format="%Y-%m-%dT%H:%M:%SZ",
  errors='ignore')).tz_localize('UTC').tz_convert('Europe/Prague'))

这适用于上面的例子,但不适用于下面的例子。 OutOfBoundsDatetime:越界纳秒时间戳

df = {'id' : [1, 2, 3],
      'timestamp' : ['2019-07-01T21:30:20Z', '2999-12-31T21:30:20Z', '9999-12-30T21:30:20Z']}

2999-12-31T21:30:20Z 或 9999-12-30T21:30:20Z 有问题。我该如何解决?

【问题讨论】:

    标签: python python-3.x pandas timestamp localtime


    【解决方案1】:

    所以 pandas 可以容纳的最大时间戳是 '2262-04-11 23:47:16.854775807'(参见 https://pandas-docs.github.io/pandas-docs-travis/user_guide/timeseries.html#timestamp-limitations)。因此,第二个和第三个时间戳都是问题所在。

    至于修复,如果您需要这些日期,我不确定是否可以帮助您。但是,您可以通过更改 errors 参数来删除它们。

    我还删除了一些你调用的函数,因为它们不需要在那里。

    df = pd.DataFrame({'id' : [1, 2, 3], 
                       'timestamp' : ['2019-07-01T21:30:20Z', 
                                      '2999-12-31T21:30:20Z', 
                                      '9999-12-30T21:30:20Z']})
    
    df['timestamp'] = pd.to_datetime(df['timestamp'], 
                                     format="%Y-%m-%dT%H:%M:%SZ", errors='coerce', utc=True)
    
    df['timestamp'] = df['timestamp'].dt.tz_convert('Europe/Prague')
    

    df.dropna() 如果您需要删除 NaT

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 2018-07-15
    • 2021-03-09
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多