2

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 

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

4 Comments

This worked great! If your 'time' column comes in a different format, you first need to convert them to nanoseconds. Eg. my time column is hours in a military format like: 0 100 1 200 ... 22 2300 23 2400 and I simply multiplied it: pd.to_timedelta(df.Hour*100000*60*60) Ideally, we would pass the format as a parameter to to_timedelta ...
@hebeha - You can use pd.to_timedelta(df.Hour, unit='h')
with the military format I get each hour multiplied by 100 if I use unit='h', and to_timedelta doesn't have the string format, it would be '%-I' in this case.
Another workaround would be 'pd.to_timedelta(data.Hour/100, unit='h')'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.