Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Date Comparisons

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.

like image 871
Ryan White Avatar asked Sep 24 '08 23:09

Ryan White


People also ask

Can we compare datetime in Python?

When you have two datetime objects, the date and time one of them represent could be earlier or latest than that of other, or equal. To compare datetime objects, you can use comparison operators like greater than, less than or equal to.


1 Answers

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) 
like image 187
John Millikin Avatar answered Sep 22 '22 15:09

John Millikin