2

I am trying to find out whether a given event happened "today" in a given timezone. My solution is based on other questions posted on S.O, particularly How do I get the UTC time of "midnight" for a given timezone?.

The basis of the solution is comparing the UTC time of midnight with the time of the event, but I get an error that the time objects cannot be compared.

The way I get midnight is as follow

def midnight_today(timezone):
    tz = pytz.timezone(timezone)
    today = datetime.now(tz).date()
    midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None)
    return midnight.astimezone(pytz.utc)

I get an error when I try

if time_in > midnight:
   print("Time-in is Today")

The error states:

  File "/home/shared/Projects/input_validation/validator/echotools.py", line 153, in is_checked_in
    if time_in > midnight:
TypeError: can't compare offset-naive and offset-aware datetimes

If I print the times, I can see they look different

print(time_in, type(time_in)
2016-12-24 10:15:52.559365 <class 'datetime.datetime'>

print(midnight, type(midnight)
2016-12-23 22:00:00+00:00 <class 'datetime.datetime'>

So my midnight function returns a time with an offset +00:00, which would be UTC, and 22:00 UTC is indeed midnight at the local time.

So I feel like I am so close to a solution but just need to get over this little hurdle....

Note: I am working in Python 3.5 and do not need to support older version of Python.

Edit: The marked duplicate question/answer helps ... but I still have a question. (Ref: How to make an unaware datetime timezone aware in python)

The answer there proposes that one can either convert the timezone naive time to timezone aware, or vica versa strip the TZ information from the aware timestamp. I tried both and both methods works.

So I can now either change the midnight_today function to be:

def midnight_today(timezone):
    tz = pytz.timezone(timezone)
    today = datetime.now(tz).date()
    midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None)
    return midnight.astimezone(pytz.utc).replace(tzinfo=None)

Or else I can change the compare line to be

midnight = midnight_today(timezonename)
if timezone(timezonename).localize(time_in) > midnight:
    print("Time-in is Today")

My question is what are the gotchas around these - are these special considerations on special days eg when DST is applied?

Community
  • 1
  • 1
The Tahaan
  • 6,915
  • 4
  • 34
  • 54

0 Answers0