Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract month from date in python

Tags:

python

pandas

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.

like image 485
dana111 Avatar asked Sep 29 '14 17:09

dana111


2 Answers

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 
like image 86
Abdelouahab Avatar answered Oct 09 '22 11:10

Abdelouahab


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 
like image 37
Michael Kramer Avatar answered Oct 09 '22 11:10

Michael Kramer