2
from pytz import timezone

import datetime
utc = datetime.timezone.utc

tz = timezone("Europe/London")
now = datetime.datetime.now(utc)
date = now.replace(tzinfo=tz)
date_utc = date.astimezone(utc)

print(now.isoformat())
print(date.isoformat())
print(date_utc.isoformat())

Might print:

2021-12-01T21:30:09.170108+00:00
2021-12-01T21:30:09.170108-00:01   <---- why does it say -00:01 here?
2021-12-01T21:31:09.170108+00:00

Why on earth is there a one minute shift? Am I missing some fundamental knowledge on time zones?

marke
  • 1,024
  • 7
  • 20
  • 1
    Does this answer your question? [Weird timezone issue with pytz](https://stackoverflow.com/questions/11473721/weird-timezone-issue-with-pytz) – FObersteiner Dec 02 '21 at 19:03
  • Note: with Python 3.9+, you have a standard lib module for this - [zoneinfo](https://docs.python.org/3/library/zoneinfo.html). [Example](https://stackoverflow.com/a/63628816/10197418). Besides, no "localize trap" there. `replace` is safe to use with ZoneInfo timezone objects. – FObersteiner Dec 02 '21 at 19:04
  • 1
    Yeah, I couldn't find this question and I was a little surprised no one every mentioned it. But somebody actually did, idk why I didn't stumble on it. Ad 2nd comment: nice, thanks for the information! – marke Dec 03 '21 at 15:57

1 Answers1

0

As per the documentation from PYTZ

Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.

You can only use localize() or astimezone() to attach PYTZ timezones to datetime objects

jezza_99
  • 1,074
  • 1
  • 5
  • 17