熊猫to_datetime失去了时区

Mat*_*ias 7 python datetime pandas

我的原始数据有一个时间戳为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()
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Mat*_*ias 8

所以这就是我解决它的方式.

有一篇关于时区和Python的精彩文章,它帮助我找到了解决方案.它依赖于ISO8601 Python包.

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]
Run Code Online (Sandbox Code Playgroud)

它产生以下输出并保留时区信息.

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