Reputation: 2495
I have a pandas datetime object, df['issue_date'] and I would like to create an object which contains only the month and year of the object, with a '0' in front of all months with single digits. All years are > 2000 I've tried:
[In]
import datetime
df['issue_year'] = pd.DatetimeIndex(lcd['issue_date']).year.astype(int)
df['issue_month'] = pd.DatetimeIndex(lcd['issue_date']).month.astype(int)
df['issue_MMYY'] = df['issue_month']*1000+df['issue_year'] % 2000
But this feels (very) kludgy and slow, and also does not pad the 0 in front. In general, date time objects give me fits....can anyone help with something more elegant?
Upvotes: 0
Views: 462
Reputation: 829
lcd = pd.DataFrame({'issue_date': pd.date_range('2015-09-01', periods=4, freq='Q')})
lcd.issue_date.apply(lambda x: x.strftime('%m%Y'))
The result:
0 092015
1 122015
2 032016
3 062016
Upvotes: 1