Search code examples
python-3.xpandasdataframedata-analysisdata-processing

Add/Subtract UTC Time to Datetime 'Time' column


I have a sample dataframe as given below.

import pandas as pd
import numpy as np

data = {'InsertedDate':['2022-01-21 20:13:19.000000', '2022-01-21 20:20:24.000000', '2022-02- 
         02 16:01:49.000000', '2022-02-09 15:01:31.000000'],
        'UTCOffset': ['-05:00','+02:00','-04:00','+06:00']}

df = pd.DataFrame(data)
df['InsertedDate'] = pd.to_datetime(df['InsertedDate'])
df

The 'InsertedDate' is a datetime column wheres the 'UTCOffset' is a string column. I want to add the Offset time to the 'Inserteddate' column and display the final result in a new column as a 'datetime' column. It should look something like this image shown below.

enter image description here

Any help is greatly appreciated. Thank you!


Solution

  • You can use pd.to_timedelta for the offset and add with time.

    # to_timedelta needs to have [+-]HH:MM:SS format, so adding :00 to fill :SS part.
    df['UTCOffset'] = pd.to_timedelta(df.UTCOffset + ':00')
    df['CorrectTime'] = df.InsertedDate + df.UTCOffset