Python Date Comparisons

PythonDatetime

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

Compare the difference to a timedelta that you create:

if datetime.datetime.now() - timestamp > datetime.timedelta(seconds = 5):
    print 'older'

Solution 3 - Python

Alternative:

if (datetime.now() - self.timestamp).total_seconds() > 100:

Assuming self.timestamp is an datetime instance

Solution 4 - Python

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

Solution 5 - Python

You can subtract two [datetime][1] objects to find the difference between them.
[1]: http://docs.python.org/lib/module-datetime.html You can use datetime.fromtimestamp to parse a POSIX time stamp.

Solution 6 - Python

Like so:

# self.timestamp should be a datetime object
if (datetime.now() - self.timestamp).seconds > 100:
    print "object is over 100 seconds old"

Solution 7 - Python

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))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyan WhiteView Question on Stackoverflow
Solution 1 - PythonJohn MillikinView Answer on Stackoverflow
Solution 2 - PythonWilliamView Answer on Stackoverflow
Solution 3 - PythonChong Ying FanView Answer on Stackoverflow
Solution 4 - PythonJerubView Answer on Stackoverflow
Solution 5 - PythonWilliam KellerView Answer on Stackoverflow
Solution 6 - PythonJeremy CantrellView Answer on Stackoverflow
Solution 7 - PythonGolden LionView Answer on Stackoverflow