Reputation: 57
I have a csv file which I get as a report and it's header looks like this:
ln;7,26;7,27;7,28;7,29;7,3;7,31;8,01;8,02;8,03;8,04;8,05;8,06;8,07;8,08;8,09;name
The numbers are supposed to be dates (so 7,29 is July 29, 7,3 is July 30). How can I convert these to actual date format if I'm using pandas? Since it's from a report, I'd need a way to format them daily automatically.
Thanks in advance!
Upvotes: 2
Views: 63
Reputation: 402493
Let's try pd.to_datetime
:
pd.to_datetime(df.columns[1:-1] + ',2018', format='%m,%d,%Y')
DatetimeIndex(['2018-07-26', '2018-07-27', '2018-07-28', '2018-07-29',
'2018-07-03', '2018-07-31', '2018-08-01', '2018-08-02',
'2018-08-03', '2018-08-04', '2018-08-05', '2018-08-06',
'2018-08-07', '2018-08-08', '2018-08-09'],
dtype='datetime64[ns]', freq=None)
Just assign the result back:
c = df.columns.tolist()
c[1:-1] = pd.to_datetime(df.columns[1:-1] + ',2018', format='%m,%d,%Y')
df.columns = c
Unfortunately, the temp list is needed because pd.Index
does not support mutable operations.
Upvotes: 2