hoof_hearted hoof_hearted - 1 year ago 240
Python Question

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:


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

Answer Source

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)
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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download