0

I ran into this problem a while back ago where parsing an ISO string with time zone data and parsing a timestamp (supposedly of the same time) will give different results. I have written a test to check this behavior and it seems pretty inconsistent:

from pytz import timezone as tz
from datetime import datetime

timezone = "Australia/Sydney"
start_time = "2021-05-04T08:12:00"
tz_object = tz(timezone)
naive_datetime = datetime.fromisoformat(start_time)


zoned_time = datetime(naive_datetime.year, naive_datetime.month, naive_datetime.day, naive_datetime.hour, naive_datetime.minute, naive_datetime.second, tzinfo=tz_object)
parsed_time = datetime.fromtimestamp(zoned_time.timestamp(), tz_object)

assert zoned_time.time() == naive_datetime.time()
assert zoned_time.time() == parsed_time.time()

This test produces the following output

  File "test.py", line 13, in <module>
    assert zoned_time.time() == parsed_time.time()
  AssertionError

Unless I'm missing something I can only conclude that the time resulting from this line

parsed_time = datetime.fromtimestamp(zoned_time.timestamp(), tz_object)

Is producing a different time than parsing the actual ISO string. Typically I'd expect the timestamp from the parsed time return a timestamp referring to 8:12 am in the time zone it was assigned.

Is this behavior expected? Did I miss something?

1 Answer 1

2

With Python 3.9, use zoneinfo. Note that there is a deprecation shim for pytz if required.

Your code then works fine like

from datetime import datetime
from zoneinfo import ZoneInfo

timezone = "Australia/Sydney"
tz_object = ZoneInfo(timezone)

start_time = "2021-05-04T08:12:00"
naive_datetime = datetime.fromisoformat(start_time)

zoned_time = datetime(naive_datetime.year, naive_datetime.month, naive_datetime.day, naive_datetime.hour, naive_datetime.minute, naive_datetime.second, tzinfo=tz_object)
parsed_time = datetime.fromtimestamp(zoned_time.timestamp(), tz_object)

assert zoned_time.time() == naive_datetime.time()
assert zoned_time.time() == parsed_time.time()

As to why you got an assertion error: with pytz you need to localize the datetime object with the time zone; never set a tzinfo directly with pytz.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.