Search code examples
pythondatetimeunix-timestamp

How to get difference between current timestamp and a different timestamp?


I am trying get difference between two timestamps and check if its greater than 30 mins

timestamp1 = 1668027512
now = datetime.now(tz)

And this is what i am trying to do

from datetime import datetime
import pytz as tz
tz = tz.timezone('UTC')
import time

timestamp1 = 1668027512
timestamp1 = datetime.utcfromtimestamp(int(timestamp1)).strftime("%Y-%m-%dT%H:%M:%S")
print(timestamp1)
now = datetime.now(tz).strftime("%Y-%m-%dT%H:%M:%S")
print(now)
print(timestamp1 - now)

This is giving me this error

TypeError: unsupported operand type(s) for -: 'str' and 'str

so i tried to convert them to unix timestamp and then do the difference

d1_ts = time.mktime(timestamp1.timetuple())
d2_ts = time.mktime(now.timetuple())

print(d1_ts - d2_ts)

But now the error is this

'str' object has no attribute 'timetuple'

This datetime package is confusing, What am i missing here ?


Solution

  • from datetime import datetime
    
    # 30 minutes times 60 seconds
    thirty_minutes = 30 * 60
    
    past_timestamp = 1668027512
    now_timestamp = datetime.now().timestamp()
    
    if (now_timestamp - past_timestamp) > thirty_minutes:
        # do your thing