【问题标题】:Pandas to_datetime loses timezone熊猫 to_datetime 失去时区
【发布时间】:2017-11-15 15:08:06
【问题描述】:

我的原始数据有一列带有 ISO8601 格式的时间戳,如下所示:

'2017-07-25T06:00:02+02:00'

由于数据是 CSV 格式,它将被读取为对象/字符串。因此,我将它转换为这样的日期时间。

import pandas pd
df['time'] = pd.to_datetime(df['time'], utc=False)

#df['time'][0]
df['time'][0].isoformat()

不幸的是,这会导致 UTC 时间戳和时区丢失。例如 df['time'][0].tzinfo 未设置。

时间戳('2017-07-25 04:00:02')

'2017-07-25T04:00:02'

我正在寻找一种方法来将时区信息保留在每个时区对象中。但之后无需将其重新设置为 CEST(中欧夏令时),因为该信息已包含在原始数据的 ISO8601 时区偏移中。知道怎么做吗?

【问题讨论】:

    标签: python pandas datetime


    【解决方案1】:

    这就是我解决它的方法。

    有一篇关于Timezones and Python 的精彩文章帮助我找到了解决方案。它依赖于ISO8601 Python packages

    import iso8601
    
    times = ['2017-07-25 06:00:02+02:00',
             '2017-07-25 08:15:08+02:00',
             '2017-07-25 12:08:00+02:00',
             '2017-07-25 13:10:12+02:00',
             '2017-07-25 15:11:55+02:00',
             '2017-07-25 16:00:00+02:00'
            ]
    
    df = pd.DataFrame(times, columns=['time'])
    df['time'] = df['time'].apply(iso8601.parse_date)
    df['time'][0]
    

    这会产生以下输出并保留时区信息。

    时间戳('2017-07-25 06:00:02+0200', tz='+02:00')

    【讨论】:

      猜你喜欢
      • 2017-08-07
      • 2020-04-17
      • 2018-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 2020-11-17
      • 2016-07-08
      相关资源
      最近更新 更多