Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to Date [With Year and Quarter]

I have a pandas dataframe, where one column contains a string for the year and quarter in the following format:

2015Q1

My Question: ​How do I convert this into two datetime columns, one for the year and one for the quarter.

like image 528
hoof_hearted Avatar asked Nov 16 '16 14:11

hoof_hearted


People also ask

How do I extract a date from a quarter in Python?

date, (x. month-1)//3 will give you the quarter (0 for first quarter, 1 for second quarter, etc -- add 1 if you need to count from 1 instead;-).

How do I convert a string to a specific date in python?

We can use date() function alongwith strptime() function to convert string to date object.


2 Answers

You could also construct a datetimeIndex and call year and quarter on it.

df.index = pd.to_datetime(df.date)
df['year'] = df.index.year
df['quarter'] = df.index.quarter

              date  year  quarter
date                             
2015-01-01  2015Q1  2015        1
2015-04-01  2015Q2  2015        2

Note that you don't even need a dedicated column for year and quarter if you have a datetimeIndex, you could do a groupby like this for example: df.groupby(df.index.quarter)

like image 59
Julien Marrec Avatar answered Nov 09 '22 13:11

Julien Marrec


You can use split, then cast column year to int and if necessary add Q to column q:

df = pd.DataFrame({'date':['2015Q1','2015Q2']})
print (df)
     date
0  2015Q1
1  2015Q2

df[['year','q']] = df.date.str.split('Q', expand=True)
df.year = df.year.astype(int)
df.q = 'Q' + df.q
print (df)
     date  year   q
0  2015Q1  2015  Q1
1  2015Q2  2015  Q2

Also you can use Period:

df['date'] = pd.to_datetime(df.date).dt.to_period('Q')

df['year'] = df['date'].dt.year
df['quarter'] = df['date'].dt.quarter

print (df)
    date  year  quarter
0 2015Q1  2015        1
1 2015Q2  2015        2
like image 10
jezrael Avatar answered Nov 09 '22 11:11

jezrael