Search code examples
pythonpandasdatetimetimedeltadatetimeoffset

pandas dataframe datetime - convert string to datetime offset


I have a dataframe like:

This time Time difference
2000-01-01 00:00:00 -3:00
2000-03-01 05:00:00 -5:00
... ...
2000-01-24 16:10:00 -7:00

I'd like to convert the 2nd column (-3:00 means minus 3 hours) from string into something like a time offest that I can directly use to operate with the 1st column (which is already in datetime64[ns]).

I thought there was supposed to be something in pd that does it but couldn't find anything straightforward. Does anyone have any clue?


Solution

  • You can use pd.to_timedelta:

    df['Time difference'] = pd.to_timedelta(df['Time difference']+':00')
    

    Obs: I used + ':00' because the default format for string conversion in pd.to_timedelta is "hh:mm:ss".