简体   繁体   中英

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.

在此处输入图像描述

Any help is greatly appreciated. Thank you!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM