PythonPython

Compare two date-times

Oct 09, 2013 · Updated: Nov 04, 2017 · by Tim Kamanin

To compare two times you need to do the following:

from datetime import datetime,timedelta
d = datetime.now()

d1 = d+timedelta(minutes=20)

if d < d1:
  print 'Hello'

When you compare django's DateTimeField value with timedelta you can get an error: "can't compare offset-naive and offset-aware datetimes", to solve this, you need to convert DateTimeField from offset-aware to offset-naive:

self.created.replace(tzinfo=None)

Now you can do a comparison.

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓