user7779326
user7779326

Reputation:

How to convert object to hour and add to date?

i have the following data frame :

correction = ['2.0','-2.5','4.5','-3.0']

date = ['2015-05-19 20:45:00','2017-04-29 17:15:00','2011-05-09 10:40:00','2016-12-18 16:10:00']

i want to convert correction as hours and add it to the date. i tried the following code, but it get the error.

df['correction'] = pd.to_timedelta(df['correction'],unit='h')
df['date'] =pd.DatetimeIndex(df['date'])
df['date'] = df['date'] + df['correction']

I get the error in converting correction to timedelta as:

ValueError: no units specified

Upvotes: 2

Views: 665

Answers (1)

jezrael
jezrael

Reputation: 862501

For me works cast to float column correction:

df['correction'] = pd.to_timedelta(df['correction'].astype(float),unit='h')
df['date'] = pd.DatetimeIndex(df['date'])
df['date'] = df['date'] + df['correction']
print (df)
         correction                date
0          02:00:00 2015-05-19 22:45:00
1 -1 days +21:30:00 2017-04-29 14:45:00
2          04:30:00 2011-05-09 15:10:00
3 -1 days +21:00:00 2016-12-18 13:10:00

Upvotes: 2

Related Questions