0

When running the following code:

d = datetime.datetime(2014, 1, 1, 8)
print d.replace(tzinfo=pytz.timezone('Asia/Jerusalem'))

I expect it to print 2014-01-01 08:00:00+02:00, but instead it prints 2014-01-01 08:00:00+02:21 (notice the strange timezone). Can someone please explain to me this strange behavior?

BTW when I print pytz.timezone('Asia/Jerusalem').localize(d), it prints '2014-01-01 08:00:00+02:00' as expected.

Tzach
  • 12,889
  • 11
  • 68
  • 115
  • Don't use `datetime.replace()`; use `timezone.localize()`. – Martijn Pieters Sep 11 '14 at 14:06
  • I already know that, but I wonder why the above code behaves like it does. – Tzach Sep 11 '14 at 14:07
  • 1
    Because the `pytz` timezones contain not just the *current* timezone offsets but also historical; e.g. they'll work correctly when you use them for a date sometime in the past. `datetime` doesn't know how to handle this correctly. – Martijn Pieters Sep 11 '14 at 14:09
  • 2
    In other words, the `Asia/Jerusalem` *at some point in the past* used an offset that was 21 minutes off. – Martijn Pieters Sep 11 '14 at 14:09
  • Thanks @MartijnPieters. I don't really understand why you marked my question as duplicate as the other question is "how to do something" and my question is "why do I get this result" – Tzach Sep 11 '14 at 14:17
  • I did make too quick an assumption that the answer there detailed that too. I'll update it. – Martijn Pieters Sep 11 '14 at 14:18
  • 1
    Perhaps things are done differently in [tag:python] questions, but I would only close as a duplicate if the *questions* are identical, not just that the other answer contains the necessary info. Is this a common moderating technique in this tag? (I'm new here) – Duncan Jones Sep 11 '14 at 14:22
  • Isn't this all explained in the pytz documentation? – Matt Johnson-Pint Sep 11 '14 at 19:05

0 Answers0