如何从datetime64获取时间偏移信息[ns]

时间:2016-06-17 09:37:16

标签: python datetime pandas dataframe timezone-offset

我正在将datetime [ns]列转换为不同的时区,结果列如下所示:

0   2011-05-25 20:30:00+02:00
1   2011-05-24 20:30:00+02:00
2   2011-05-20 20:30:00+02:00
3   2011-05-19 20:30:00+02:00
4   2011-05-15 13:30:00+02:00

我正在尝试提取偏移量信息,+02:00

offset = converted.apply(lambda x: x.strftime('%z'))

但它给了我一个空白栏目。

当列为dtype == object / str时,offest信息会消失,因此无法将其与正则表达式一起使用。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我认为你需要strftime

print (df)
                       date
0 2011-05-25 20:30:00+02:00
1 2011-05-24 20:30:00+02:00
2 2011-05-20 20:30:00+02:00
3 2011-05-19 20:30:00+02:00
4 2011-05-15 13:30:00+02:00

print (df.date.dt.tz)
Europe/Bratislava

df['timezone'] = df.date.dt.strftime('%z')
print (df)
                       date timezone
0 2011-05-25 20:30:00+02:00    +0200
1 2011-05-24 20:30:00+02:00    +0200
2 2011-05-20 20:30:00+02:00    +0200
3 2011-05-19 20:30:00+02:00    +0200
4 2011-05-15 13:30:00+02:00    +0200

如果dtype列的dateobject/string,请使用indexing with str

df['date'] = df.date.astype(str)
df['timezone'] = df.date.str[-6:]
print (df)
                        date timezone
0  2011-05-25 20:30:00+02:00   +02:00
1  2011-05-24 20:30:00+02:00   +02:00
2  2011-05-20 20:30:00+02:00   +02:00
3  2011-05-19 20:30:00+02:00   +02:00
4  2011-05-15 13:30:00+02:00   +02:00
相关问题