Reputation: 597
I've got the following Pandas DataFrame:
date hour
20140101 0
20140101 1
20140101 2
20140101 3
20140101 4
... ...
I want to combine these two to a datetime column. I've tried the following, but I get an error because I'm using Windows, I think:
wdf['date'] = wdf['date'].astype(str) + ' ' + wdf['hour'].astype(str)
wdf['date'] = pd.to_datetime(wdf['date'], format='%Y%m%d %-H')
ValueError: '-' is a bad directive in format '%Y%m%d %-H'
I've tried %#H
, but that resulted in a similar error. I have to use the dash or pound sign, because the hour notation is a single decimal.
Upvotes: 1
Views: 89
Reputation: 13403
I'd try using zfill
to pad with 0
where needed, and use the regular %H
.
try this:
wdf['date'] = wdf['date'].astype(str) + ' ' + wdf['hour'].astype(str).str.zfill(2)
wdf['date'] = pd.to_datetime(wdf['date'], format='%Y%m%d %H')
Output:
date hour
0 2014-01-01 00:00:00 0
1 2014-01-01 01:00:00 1
2 2014-01-01 02:00:00 2
3 2014-01-01 03:00:00 3
4 2014-01-01 04:00:00 4
Upvotes: 1