Reputation: 1917
I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to:
if (datetime.now() - self.timestamp) > 100
# Where 100 is either seconds or minutes
This generates a type error.
What is the proper way to do date time comparison in python? I already looked at WorkingWithTime which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison.
Please post lists of datetime best practices.
Upvotes: 64
Views: 67245
Reputation: 4233
Convert your time delta into seconds and then use conversion back to hours elapsed and remaining minutes.
start_time=datetime(
year=2021,
month=5,
day=27,
hour=10,
minute=24,
microsecond=0)
end_time=datetime.now()
delta=(end_time-start_time)
seconds_in_day = 24 * 60 * 60
seconds_in_hour= 1 * 60 * 60
elapsed_seconds=delta.days * seconds_in_day + delta.seconds
hours= int(elapsed_seconds/seconds_in_hour)
minutes= int((elapsed_seconds - (hours*seconds_in_hour))/60)
print("Hours {} Minutes {}".format(hours,minutes))
Upvotes: 0
Reputation: 200746
Use the datetime.timedelta
class:
>>> from datetime import datetime, timedelta
>>> then = datetime.now() - timedelta(hours = 2)
>>> now = datetime.now()
>>> (now - then) > timedelta(days = 1)
False
>>> (now - then) > timedelta(hours = 1)
True
Your example could be written as:
if (datetime.now() - self.timestamp) > timedelta(seconds = 100)
or
if (datetime.now() - self.timestamp) > timedelta(minutes = 100)
Upvotes: 111
Reputation: 51
Alternative:
if (datetime.now() - self.timestamp).total_seconds() > 100:
Assuming self.timestamp is an datetime instance
Upvotes: 5
Reputation: 42608
You can use a combination of the 'days' and 'seconds' attributes of the returned object to figure out the answer, like this:
def seconds_difference(stamp1, stamp2):
delta = stamp1 - stamp2
return 24*60*60*delta.days + delta.seconds + delta.microseconds/1000000.
Use abs() in the answer if you always want a positive number of seconds.
To discover how many seconds into the past a timestamp is, you can use it like this:
if seconds_difference(datetime.datetime.now(), timestamp) < 100:
pass
Upvotes: 1
Reputation: 27416
Like so:
# self.timestamp should be a datetime object
if (datetime.now() - self.timestamp).seconds > 100:
print "object is over 100 seconds old"
Upvotes: 0
Reputation: 5400
You can subtract two datetime objects to find the difference between them.
You can use datetime.fromtimestamp
to parse a POSIX time stamp.
Upvotes: 0
Reputation: 6428
Compare the difference to a timedelta that you create:
if datetime.datetime.now() - timestamp > datetime.timedelta(seconds = 5):
print 'older'
Upvotes: 5