You can use pd.to_datetime
's format arg:
In [11]: s = pd.Series(["29062017", "01AUG2017"])
In [12]: pd.to_datetime(s, format="%d%m%Y", errors="coerce")
Out[12]:
0 2017-06-29
1 NaT
dtype: datetime64[ns]
In [13]: pd.to_datetime(s, format="%d%b%Y", errors="coerce")
Out[13]:
0 NaT
1 2017-08-01
dtype: datetime64[ns]
Note: the coerce
argument means that failures will be NaT
.
and fill in the NaN
s from one into the other e.g. using fillna
:
In [14]: pd.to_datetime(s, format="%d%m%Y", errors="coerce").fillna(pd.to_datetime(s, format="%d%b%Y", errors="coerce"))
Out[14]:
0 2017-06-29
1 2017-08-01
dtype: datetime64[ns]
Any strings that don't match either format will remain NaT.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…