pandas get timestamp difference in milliseconds as integer

Viewed 1510

How can I get the millisecond difference between these two timestamps in pandas as an integer?

My attempt so far:

import pandas as pd
from datetime import datetime


ts1 = datetime(2018, 1, 1, 22, 36, 9, 38000)
ts2 = datetime(2018, 1, 1, 22, 36, 7, 908000)


df = pd.DataFrame("ts1": [ts1],"ts2": [ts2]})


df['interval_ts'] = df['ts1'] - df['ts2']

df['interval_ts'] = df['interval_ts'].apply(lambda x: x.microseconds / 1000)

My expected output is: 1130

1 Answers

Use total_seconds, multiple by 1000 and cast to integer:

df['interval_ts'] = ((df['ts1'] - df['ts2']).dt.total_seconds() * 10**3).astype(int)

Or convert to native numpy format and divide 10**6:

df['interval_ts1'] = ((df['ts1'] - df['ts2']).astype(np.int64) / 10**6).astype(int)
print (df)
                      ts1                     ts2  interval_ts  interval_ts1
0 2018-01-01 22:36:09.038 2018-01-01 22:36:07.908         1130          1130
Related