简体   繁体   中英

Pandas dataframe combine two columns to get datetime column

Given the dataframe below where uptime is time in nanoseconds, how to combine columns date_is with uptime to form a new column of type datetime object.

    date_is              uptime     
0   14/05/2016 10:54:33  11537640270059 
1   14/05/2016 10:54:33  11537650128140 
2   14/05/2016 10:54:33  11537659894659 
3   14/05/2016 10:54:33  11537679549779 
4   14/05/2016 10:54:33  11537699204899 

Use to_datetime + to_timedelta :

df['new'] = pd.to_datetime(df['date_is']) + pd.to_timedelta(df['uptime'])
print (df)
               date_is          uptime                           new
0  14/05/2016 10:54:33  11537640270059 2016-05-14 14:06:50.640270059
1  14/05/2016 10:54:33  11537650128140 2016-05-14 14:06:50.650128140
2  14/05/2016 10:54:33  11537659894659 2016-05-14 14:06:50.659894659
3  14/05/2016 10:54:33  11537679549779 2016-05-14 14:06:50.679549779
4  14/05/2016 10:54:33  11537699204899 2016-05-14 14:06:50.699204899

Is possible also converted columns assign back:

df['date_is'] = pd.to_datetime(df['date_is'])
df['uptime'] = pd.to_timedelta(df['uptime'])
df['new'] = df['date_is'] + df['uptime']
print (df)
              date_is          uptime                           new
0 2016-05-14 10:54:33 03:12:17.640270 2016-05-14 14:06:50.640270059
1 2016-05-14 10:54:33 03:12:17.650128 2016-05-14 14:06:50.650128140
2 2016-05-14 10:54:33 03:12:17.659894 2016-05-14 14:06:50.659894659
3 2016-05-14 10:54:33 03:12:17.679549 2016-05-14 14:06:50.679549779
4 2016-05-14 10:54:33 03:12:17.699204 2016-05-14 14:06:50.699204899

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