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:
JavaScript
x
3
1
if (datetime.now() - self.timestamp) > 100
2
# Where 100 is either seconds or minutes
3
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.
Advertisement
Answer
Use the datetime.timedelta
class:
JavaScript
1
8
1
>>> from datetime import datetime, timedelta
2
>>> then = datetime.now() - timedelta(hours = 2)
3
>>> now = datetime.now()
4
>>> (now - then) > timedelta(days = 1)
5
False
6
>>> (now - then) > timedelta(hours = 1)
7
True
8
Your example could be written as:
JavaScript
1
2
1
if (datetime.now() - self.timestamp) > timedelta(seconds = 100)
2
or
JavaScript
1
2
1
if (datetime.now() - self.timestamp) > timedelta(minutes = 100)
2