python-3.x - 熊猫解析具有时区偏移的日期不返回日期时间的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 转换我的时间,然后返回一种日期时间,而不是类型对象?
非常感谢任何帮助,谢谢!
解决方案
这是不可能的 - pandas TimeSeries 需要相同offset
的。
如果检查type
s 它返回每个datetime
正确的偏移量,所以很遗憾不能使用矢量化的 datetimelike 函数,因为输出是Series
s 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
推荐阅读
- elasticsearch - Logstash 索引未反映在 Kibana 中
- uwp - 安装 UWP 应用返回未经授权的错误
- google-apps-script - google apps 脚本创建的 html 发布在 Google Docs 中,从今天开始出现错误
- jmeter - 通过java代码添加jmeter用户参数预处理器
- scala - Spark SQL:如果存在则更新,否则忽略
- javascript - 使用来自 servlet 的上一个表单值重定向回上一个 jsp 页面
- image - TclError:图像“pyimage68”不存在
- javascript - 两个点击事件同时工作
- html - 如何访问 html 文件中 manifest.json 中映射的文件?
- spring-boot - SpringBoot 使用 ControllerAdvice 中的自定义错误处理所有错误