python将字符串(Mar18)转换为Dateformat(201803)

2024-09-26 22:52:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个值为Mar18,Apr18,Jun18的列。 我正在尝试转换成201803,201804,201806这样的日期格式。 我写了我的语法如下:

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

这给了我一个2018-03-01,2018-04-01,2018-06-01列。你知道吗

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

我应该使用什么格式类型。你知道吗

你知道吗注意:如果是一个重复的问题,请指给我上一个问题。你知道吗

谢谢


Tags: toformat类型dfdatetime格式语法column
1条回答
网友
1楼 · 发布于 2024-09-26 22:52:31
In [19]: pd.to_datetime(['Mar2018'],format='%b%Y').strftime('%Y%m')
Out[19]: Index(['201803'], dtype='object')

请注意,这是而不是日期时间数据类型-这是字符串数据类型

或者,您可以将其转换为^{} 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

相关问题 更多 >

    热门问题