0

Some time ago, I had to write a small script in python that, among others, parsed ISO8601-formatted date string and compared it with the current datetime.

As I do not code in Python, I was looking around for a solution. To my big disappointment, all suggested solutions that I found suggested using third-party libraries to accomplish the job. Essentially, I ended up doing this (simplified for brevity):

import iso8601
import pytz

utc = pytz.UTC()
event_date = iso8601.parse_date('2002-10-02T15:00:00.05Z')
now = utc.localize(datetime.utcnow())

# Only now I was able to compare the dates
if event_date - timedelta(hours=3) < now:
    <do something>

I am not comfortable with the fact that I had to import two third-party libraries for such common task.

How can I accomplish the above with only what's only available in the Python standard lib and avoid errors like:

  • can't compare offset-naive and offset-aware datetimes
  • cannot compare tz-naive and tz-aware datetime-like objects
luqo33
  • 8,001
  • 16
  • 54
  • 107
  • Did you see this topic: https://stackoverflow.com/questions/8142364/how-to-compare-two-dates – Denis Rasulev Nov 16 '18 at 09:22
  • 2
    Datetime module should help – artona Nov 16 '18 at 09:24
  • @DenisRasulev, these are not the same, in the topic you pasted homogeneous dates are compared. There is an array of problems when you attempt to compare dates instantiated differently (e.g. parsed from ISO8601). – luqo33 Nov 16 '18 at 10:45

0 Answers0