Search code examples
pythondatetimetimestampepochtimedelta

Python3 check if int epochtime are less then X hours diff


I have two ints that represents epochtimes:

x1 = 1597611600
x2 = 1597489203

I want to check if there is less then 72 hours between them. What is the best way to do so in Python3? Please notice that both are int.


Solution

  • You can convert epoch timestamps to datetime objects, perform subtraction and compare the result to timedelta object. However, you can simply do a comparision in seconds.

    from datetime import datetime as dt, timedelta as td
    def epoch_diff_within(ts1, ts2, hr):
        d1 = dt.fromtimestamp(x1)
        d2 = dt.fromtimestamp(x2)
        return d1 - d2 < td(hours=hr)
    
    def epoch_diff_within2(ts1, ts2, hr):
        return ts1 - ts2 < hr * 60 * 60
    
    x1 = 1597611600
    x2 = 1597489203
    print(epoch_diff_within(x1, x2, 72)) # Output: True
    print(epoch_diff_within2(x1, x2, 72)) # Output: True
    print(epoch_diff_within(x1, x2, 24)) # Output: False
    print(epoch_diff_within2(x1, x2, 24)) # Output: False