38

I have a column of dates in the format 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.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
dana111
  • 429
  • 1
  • 5
  • 5

4 Answers4

77
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
Abdelouahab
  • 7,331
  • 11
  • 52
  • 82
  • 2
    except the question asks for the month – Padraic Cunningham Sep 29 '14 at 17:55
  • 5
    @PadraicCunningham I would hope the OP wouldn't need so much hand-holding that they would see "then extract the year" and think "but wait, I really wanted to extract the month! I can't use this answer!" – SethMMorton Sep 29 '14 at 17:57
  • 4
    @SethMMorton, well the answer does not actually show how to extract the year either so unless you have used datetime before it may not be obvious to a beginner. – Padraic Cunningham Sep 29 '14 at 18:01
  • Using the code, I am getting: AttributeError: type object 'datetime.datetime' has no attribute 'datetime' – qqqqq Apr 16 '22 at 23:00
25

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
Matt Ke
  • 3,599
  • 12
  • 30
  • 49
Michael Kramer
  • 259
  • 3
  • 2
5
>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'
g4ur4v
  • 3,210
  • 5
  • 32
  • 57
3

if you use datetime, you can simply add .month at the end of the datetime method

>>> 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
Koops
  • 422
  • 3
  • 11
  • 1
    I understand it is not directly answering the question, but at the same time, it is also addressing the splitting of date formatting. This might come in handy to someone who is having a similar problem. – Koops Jan 03 '22 at 17:38