摘录数据:
Givent以下pandas dataframe示例:
df =
index date
7838 2012 January
7790 2012 January
7853 2015 September
7889 2016 March
7928 2015 October
7847 1999 January
7884 2006 January
7826 1992 January
是否有简单(和pythonic)方式将自由文本转换为标准日期时间变量?类似的东西:
df =
index date
7838 2012-01-01
7790 2012-01-01
7853 2015-09-01
7889 2016-03-01
7928 2015-10-01
7847 1999-01-01
7884 2006-01-01
7826 1992-01-01
答案 0 :(得分:2)
使用pd.to_datetime()从文本转换为日期类型。您可以从此list收集相应的日期类型。
df['date'] = pd.to_datetime(df['date'], format='%Y %B')
答案 1 :(得分:2)
to_datetime
在没有任何特定格式说明符的情况下处理此罚款:
In [83]:
pd.to_datetime(df['date'])
Out[83]:
0 2012-01-01
1 2012-01-01
2 2015-09-01
3 2016-03-01
4 2015-10-01
5 1999-01-01
6 2006-01-01
7 1992-01-01
Name: date, dtype: datetime64[ns]