Home > front end >  How to get difference between current timestamp and a different timestamp?
How to get difference between current timestamp and a different timestamp?

Time:11-29

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 ?

CodePudding user response:

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

CodePudding user response:

The problem you are facing is that when you use .strftime("%Y-%m-%dT%H:%M:%S") you are converting the class datetime to string and you can't compare strings.

I suggest you to only utilize yours variables as strings at the moment you are printing them (but that depends on your goals with the variables).

Also, from this you can solve the problem with datetime operations that are build upon a specific timezone. For this you have to include the now = now.replace(tzinfo=None)

So your code would be

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

timestamp1 = 1668027512
timestamp1 = datetime.utcfromtimestamp(int(timestamp1))

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

now = now.replace(tzinfo=None)
print(timestamp1 - now)

CodePudding user response:

I recommend to always work with aware datetimes in order to avoid issues and ensure reproducibility, especially if you'd like to share your code.

utcfromtimestamp() unfortunately returns a naive datetime, meaning it doesn't set the tzinfo attribute. It's better to use fromtimestamp() and specify the timezone.

From pytz you can directly import the UTC constant, for convenience.

You can use timedelta() to express the time delta.

Parenthesis are not mandatory in the comparison, thanks to the operator precedence rules

from datetime import datetime, timedelta
from pytz import UTC

dt1 = datetime.fromtimestamp(1668027512, UTC)
now = datetime.now(UTC)
if now - dt1 > timedelta(minutes=30):
    print("period expired")
  • Related