使用pd.to_datetime处理多种日期时间格式 [英] Handling multiple datetime formats with pd.to_datetime
本文介绍了使用pd.to_datetime处理多种日期时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个datatime数据,其格式类似于29062017
和01AUG2017
.
如您所见,月份位于数据中间.
I have a datatime data, their format is like 29062017
and 01AUG2017
.
As you can see, the month is in the middle of data.
当我使用pd.to_datetime
时,我想将此数据转换为日期时间,但是它不起作用.
I want to convert this data to datetime, when I use pd.to_datetime
, but it doesn't work.
您知道解决此问题的好方法吗?
Do you know a good way to solve this problem?
推荐答案
替代方法是使用映射器和replace
用数值等效项替换月份代码:
The alternative would be to use a mapper and replace
to substitute month codes with their numerical equivalent:
s = pd.Series(["29062017", "01AUG2017"]); s
0 29062017
1 01AUG2017
dtype: object
m = {'JAN' : '01', ..., 'AUG' : '08', ...} # you fill in the rest
s = s.replace(m, regex=True); s
0 29062017
1 01082017
dtype: object
现在您只需要一个pd.to_datetime
呼叫:
Now all you need is a single pd.to_datetime
call:
pd.to_datetime(s, format="%d%m%Y", errors="coerce")
0 2017-06-29
1 2017-08-01
dtype: datetime64[ns]
这篇关于使用pd.to_datetime处理多种日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文