python转换字符串(Mar18)到Dateformat(201803)

时间:2018-06-18 17:40:33

标签: python pandas

我的列有Mar18,Apr18,Jun18之类的值。 我想转换为201803,201804,201806之类的dateformat。 我写了如下语法:

pd.to_datetime(df['column'],format'%b%y')

这给了我2018-03-01,2018-04-01,2018-06-01列。

如何将其转换为日期数据类型,如201803,201804,201806

我应该使用什么格式类型。

注意:如果这是一个重复的问题,请指出我之前的问题。

由于

1 个答案:

答案 0 :(得分:0)

In [19]: pd.to_datetime(['Mar2018'],format='%b%Y').strftime('%Y%m')
Out[19]: Index(['201803'], dtype='object')

PS请注意,这是日期时间dtype - 这是一个字符串dtype

或者您可以将其转换为period dtype

In [28]: df
Out[28]:
    column
0  Aug2014
1  Mar2018
2  Jan2017
3  Jun2016

In [29]: df['new'] = pd.to_datetime(df['column'], format='%b%Y').dt.to_period('M')
In [30]: df
Out[30]:
    column     new
0  Aug2014 2014-08
1  Mar2018 2018-03
2  Jan2017 2017-01
3  Jun2016 2016-06

In [31]: df.dtypes
Out[31]:
column    object
new       object
dtype: object

In [32]: df['new'].dt.daysinmonth
Out[32]:
0    31
1    31
2    31
3    30
Name: new, dtype: int64