0

I have a list of timestamps and want to loop through them and see if the time-delta between each of them is greater than 4 hours here is some pseudo code I tried but I do not know the syntax in pandas:

timestamps = ["7/20/2020  12:38:39 AM", "7/20/2020  2:50:46 AM","7/25/2020  7:18:55 PM"]

for x in range(0,len(timestamps)-1):
    t1 = timestamps[x]
    t2 = time[timestamps[x+1]
    if (t2 - t1) >4 hours:
        print('Greater Than 4 hours!')
angle_201
  • 15
  • 4

2 Answers2

1

You need to use datetime module from datetime library:

import datetime as dt
timestamps = ["7/20/2020  12:38:39 AM", "7/20/2020  2:50:46 AM","7/25/2020  7:18:55 PM"]

for x in range(0,len(timestamps)-1):
    t1 = dt.datetime.strptime(timestamps[x], "%m/%d/%Y  %H:%M:%S %p")
    t2 = dt.datetime.strptime(timestamps[x+1], "%m/%d/%Y  %H:%M:%S %p")
    if (t2 - t1) > dt.timedelta(hours=4):
        print(x, 'Greater Than 4 hours!')
    else:
        print(x, 'Not Greater Than 4 hours!')

Alternately, you could also try using the below instead of timedelta:

from dateutil.relativedelta import relativedelta

pd.to_datetime() is also an option but pandas being a heavy library, I would stay away from it unless already using it at other places in my code.

0

Hopefully, this answers your question:

import pandas as pd
timestamps = ["7/20/2020  12:38:39 AM", "7/20/2020  2:50:46 AM","7/25/2020  7:18:55 PM"]
timestamps = pd.to_datetime(timestamps)

for i in range(0,len(timestamps)-1):
    t1 = timestamps[i]
    t2 = timestamps[i+1]
    diff = (t2 - t1).seconds / 3600
    if diff > 4:
        print('Greater Than 4 hours!')
S Haskin
  • 31
  • 5