从日期时间对象中提取日期和月份 [英] Extract day and month from a datetime object

查看:93
本文介绍了从日期时间对象中提取日期和月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一列日期为字符串格式为'2017-01-01'的日期。有没有办法使用大熊猫从中提取日期和月份?

I have a column with dates in string format '2017-01-01'. Is there a way to extract day and month from it using pandas?

我已将列转换为 datetime dtype 但没有弄清楚后面的部分:

I have converted the column to datetime dtype but haven't figured out the later part:

df['Date'] =  pd.to_datetime(df['Date'], format='%Y-%m-%d')

df.dtypes: 
Date        datetime64[ns]

print(df)

         Date
0   2017-05-11
1   2017-05-12
2   2017-05-13 


推荐答案

具有 dt.day dt.month --- Series.dt

With dt.day and dt.month --- Series.dt

df = pd.DataFrame({'date':pd.date_range(start='2017-01-01',periods=5)})
df.date.dt.month
Out[164]: 
0    1
1    1
2    1
3    1
4    1
Name: date, dtype: int64

df.date.dt.day
Out[165]: 
0    1
1    2
2    3
3    4
4    5
Name: date, dtype: int64

也可以使用 dt.strftime

Also can do with dt.strftime

df.date.dt.strftime('%m')
Out[166]: 
0    01
1    01
2    01
3    01
4    01
Name: date, dtype: object

这篇关于从日期时间对象中提取日期和月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆