2

I am not sure what is going wrong with the following snippet of code:

from datetime import datetime
import pytz
time_us_pacific = datetime(2017, 3, 16, 14, 30).replace(tzinfo=pytz.timezone("America/Los_Angeles"))
time_india = time_us_pacific.astimezone(pytz.timezone("Asia/Kolkata"))
print(time_india)
# Actual: 2017-03-17 03:53:00+05:30
# Expected: 2017-03-17 03:00:00+05:30

# Picking a date before DST switch:
time_us_pacific = datetime(2017, 2, 16, 14, 30).replace(tzinfo=pytz.timezone("America/Los_Angeles"))
time_india = time_us_pacific.astimezone(pytz.timezone("Asia/Kolkata"))
print(time_india)
# Actual: 2017-03-17 03:53:00+05:30
# Expected: 2017-03-17 04:00:00+05:30

There seem to be two issues:

  1. pytz timezones are not accounting for DST
  2. The India timezone seems to prefer the more arcane local mean time (LMT) as opposed to Indian Standard Time

My application needs to do some serious timezone-based accounting of events and cannot afford to screw things up. My questions are:

  1. Am I using Python datetime and pytz incorrectly?
  2. Should I be using something else in place of pytz?

Thanks for any help or insights.

Raj
  • 2,852
  • 4
  • 29
  • 48
  • 1
    Hi @Raj, it is a known defect as [its highlighted here](http://stackoverflow.com/a/25390097/227884). Gist of the answer is: `datetime(..).replace(tzinfo=timezone_object)` should not be used. if you rewrite as: `timezone_object.localize(datetime(.....))`, you wont have that issue. – UltraInstinct Mar 19 '17 at 03:17
  • Thanks @SuperSaiyan! This works! – Raj Mar 19 '17 at 20:10

0 Answers0