1

According to Convert UTC to local time to UTC in Python and Google App Engine, to correctly compare the times of now and a target time (considering different time zones), I have to convert the target time to UTC as follows:

import pytz

def toUTC(date, tz):
    tz = pytz.timezone('Asia/Taipei')
    utc = pytz.timezone('UTC')
    d_tz = tz.normalize(tz.localize(date))
    d_utc = d_tz.astimezone(utc)
    return d_utc

days = 10
minutes = 20
targetTime = datetime.datetime(2012,12,22,0,0,0)
targetTime = targetTime + datetime.timedelta(days=days, minutes=minutes)
targetTime = toUTC(targetTime) 

if targetTime < datetime.datetime.now():
    ...

Questions:

  1. Is this correct?
  2. There is an error message:

    TypeError: can't compare offset-naive and offset-aware datetimes

    How to solve it?

Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
Randy Tang
  • 4,283
  • 12
  • 54
  • 112

1 Answers1

1

its because one of your datetime objects has a timezone set and the other one doesn't.
take a look here and here

Community
  • 1
  • 1
aschmid00
  • 7,038
  • 2
  • 47
  • 66