简体   繁体   English

从python中的日期中提取月份

[英]extract month from date in python

I have a column of dates in the format 2010-01-31.我有一列日期格式为 2010-01-31。 I can extract the year using我可以使用提取年份

#extracting year
year = df["date"].values
year = [my_str.split("-")[0] for my_str in year]
df["year"] = year

I'm trying to get the month, but I don't understand how to get it on the second split.我试图得到这个月,但我不明白如何在第二次分裂中得到它。

import datetime

a = '2010-01-31'

datee = datetime.datetime.strptime(a, "%Y-%m-%d")


datee.month
Out[9]: 1

datee.year
Out[10]: 2010

datee.day
Out[11]: 31

Alternate solution替代解决方案

Create a column that will store the month:创建一个将存储月份的列:

data['month'] = data['date'].dt.month

Create a column that will store the year:创建一个列来存储年份:

data['year'] = data['date'].dt.year
>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'

if you use datetime , you can simply add .month at the end of the datetime method如果你使用datetime ,你可以简单地在 datetime 方法的末尾添加.month

>>> from datetime import datetime, date, time, timedelta, timezone
>>> datetime.now()
datetime.datetime(2022, 1, 3, 11, 33, 16, 609052)
>>> datetime.now().date()
datetime.date(2022, 1, 3)
>>> datetime.now().date().month
1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM