首页 > 解决方案 > 熊猫解析具有时区偏移的日期不返回日期时间的dtype,只是对象?

问题描述

我有一个时区偏移量为 +01:00 和 +00:00 的日期列,因此时间偏移量不同,但应保持相同的格式。例如

2019-05-21T00:00:00+01:00
2018-12-10T00:00:00+00:00

我试图通过让熊猫自动定义时间来解析这个:

pd.to_datetime(df['Effective_Date'])

这只是将列从

2019-05-06T00:00:00+01:00
to
2019-05-06 00:00:00+01:00

然而,当我运行时,我的列df.dtypes仍然是对象类型 - 我认为这是由于不同的时间偏移差异造成的?

也试过

pd.to_datetime(df['Effective_Date'], format='%Y-%m-%dT%H:%M:%S%z')

但这也不起作用

如何让 pandas 转换我的时间,然后返回一种日期时间,而不是类型对象?

非常感谢任何帮助,谢谢!

标签: python-3.xpandastimezone-offset

解决方案


这是不可能的 - pandas TimeSeries 需要相同offset的。

如果检查types 它返回每个datetime正确的偏移量,所以很遗憾不能使用矢量化的 datetimelike 函数,因为输出是Seriess datetime

print (pd.to_datetime(df['Effective_Date']))
0    2019-05-21 00:00:00+01:00
1    2018-12-10 00:00:00+00:00
Name: Effective_Date, dtype: object

print (pd.to_datetime(df['Effective_Date']).apply(type))
0    <class 'datetime.datetime'>
1    <class 'datetime.datetime'>
Name: Effective_Date, dtype: object

检查差异:

print (df)
              Effective_Date
0  2019-05-21T00:00:00+01:00
1  2018-12-10T00:00:00+01:00

print (pd.to_datetime(df['Effective_Date']))
0   2019-05-21 00:00:00+01:00
1   2018-12-10 00:00:00+01:00
Name: Effective_Date, dtype: datetime64[ns, pytz.FixedOffset(60)]

print (pd.to_datetime(df['Effective_Date']).apply(type))
0    <class 'pandas._libs.tslibs.timestamps.Timesta...
1    <class 'pandas._libs.tslibs.timestamps.Timesta...
Name: Effective_Date, dtype: object

推荐阅读