1

How can I get the ms from the first timecode until each subsequent timecode in a series?

import pandas as pd

s = {1: pd.Timestamp('1970-01-28 05:28:52.235000'),
     2: pd.Timestamp('1971-02-02 12:13:23.230000'),
     3: pd.Timestamp('1970-09-04 17:14:53.120000')}

f = pd.DataFrame().from_dict(s, orient='index')

I have absolutely no idea how to do this and have tried googling without much luck.

ALollz
  • 57,915
  • 7
  • 66
  • 89
syntheso
  • 437
  • 3
  • 17

2 Answers2

0

Subtracting two TimeStamps gives you a Timedelta which you can convert to a float with .dt.total_seconds(). Use .iloc[0] to subtract the first element from the entire Series.

(f[0]-f[0].iloc[0]).dt.total_seconds()*1000
                                      # because milliseconds

#1    0.000000e+00
#2    3.199227e+10
#3    1.896396e+10
#Name: 0, dtype: float64
ALollz
  • 57,915
  • 7
  • 66
  • 89
  • This gave me AttributeError: 'Timestamp' object has no attribute 'iloc' – syntheso Mar 27 '19 at 22:54
  • @syntheso Do you have a DataFrame, as in your example, or a `Series`. If `f` is a Series then it should be `(f-f.iloc[0]).dt.total_seconds()*1000` – ALollz Mar 27 '19 at 23:09
0

Go after this using DataFrame operations so that Pandas does the work. total_delta_time_ms shows the millisecond difference between the first value and each subsequent value. row_delta_time_ms shows the milliseconds between each row.

import pandas as pd
from pandas import Timestamp
import numpy as np
import time

s = {1: Timestamp('1970-01-28 05:28:52.235000'),
 2: Timestamp('1971-02-02 12:13:23.230000'),
 3: Timestamp('1970-09-04 17:14:53.120000')}

f = pd.DataFrame().from_dict(s, columns=["start_time"], orient='index')
f["first_time"] = f["start_time"].values[0]
f["end_time"] = f["start_time"].shift(1)

f["total_delta_time"] = f["start_time"] - f["first_time"]
f["total_delta_time_ms"] = f["total_delta_time"].astype(np.int64) // 10**9

f["row_delta_time"] = f["start_time"] - f["end_time"]
f["row_delta_time_ms"] = f["row_delta_time"].astype(np.int64) // 10**9

print(f[["total_delta_time", "total_delta_time_ms"]])

Rich Andrews
  • 1,590
  • 8
  • 12