0

I want to check if the us/pacific time is after 9am.

However, when I compare the times, it still says 'False' even after 9. At 10am it says 'True'

# get us/pacific time
import pytz
tz = pytz.timezone('US/Pacific')

# get the time now and put it in us/pacific
from datetime import datetime
tmp_date = tz.fromutc(datetime.utcnow())

# make a threshold that is the same but hour = 9
tmp_date_threshold = datetime(year=tmp_date.year,month=tmp_date.month,day=tmp_date.day,hour=9,tzinfo=tz)

# see what the times are
>>> tmp_date
datetime.datetime(2022, 6, 20, 6, 33, 9, 810387, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)
>>> tmp_date_threshold
datetime.datetime(2022, 6, 20, 9, 0, tzinfo=<DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>)

# compare (expected)
>>> tmp_date > tmp_date_threshold
False

# add 3 hours to make it after 9am
tmp_date = tmp_date + timedelta(hours=3)

# now after 9am
>>> tmp_date
datetime.datetime(2022, 6, 20, 9, 33, 9, 810387, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)

# compare again
# still false
>>> tmp_date > tmp_date_threshold
False

Howcome is my comparison still failing even through tmp_date is after 9? And howcome is my timezone info different for each object even though I used the same tz object to make each?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
user37216
  • 11
  • 2
  • 1
    because you set the tzinfo to `tmp_date_threshold` directly instead of using the `localize` method of the timezone object - which you *must* do with pytz. Btw. you can also simplify `tmp_date = datetime.now(tz)` to get the current time in timezone tz. – FObersteiner Jun 20 '22 at 14:42
  • Does this answer your question? [Weird timezone issue with pytz](https://stackoverflow.com/questions/11473721/weird-timezone-issue-with-pytz) – FObersteiner Jun 20 '22 at 14:43

0 Answers0