0

I'm wrestling with what appears to be a common timezone issue in Python, but have not been able to solve it or find the exact issue I'm running into here on SO, so I pose the question below.

I have a timetuple that does not have a timezone set. I also have a timezone. And I have the computer in a different timezone. How do I convert the time to the local time taking DST into account?

>>> type(dt.value)
<type 'datetime.datetime'>
>>> print dt.timetuple()
time.struct_time(tm_year=2012, tm_mon=6, tm_mday=28, ..., tm_isdst=-1)
>>> print somezone.zone
America/New_York

If I add the zone info to dt as follows, DST isn't handled properly... tm_isdst always shows up as zero, regardless of the month being in DST or not.

dt.value = dt.value.replace(tzinfo=somezone)
>>> print dt.timetuple()
time.struct_time(tm_year=2012, tm_mon=6, tm_mday=28, ..., tm_isdst=0)
mankoff
  • 2,225
  • 6
  • 25
  • 42

1 Answers1

1

Use the pytz library. It will let you easily do this.

from pytz import timezone
zone_tz = timezone(zone)
zone_aware_dt = zone_tz.localize(dt)
local_tz = timezone("America/Los_Angeles")
local_dt = local_tz.normalize(zone_aware_dt)
Amber
  • 507,862
  • 82
  • 626
  • 550
  • I'm using `pytz` and know that is the solution, but am not sure how to do it. Also, I'm fixing a TZ bug in someone else code (and I'm not much of a python programmer), so I can't rebuild their entire existing solution... – mankoff Sep 30 '12 at 06:14
  • How do I determine `local_tz` programatically? – mankoff Sep 30 '12 at 06:16
  • There isn't a guaranteed way, unfortunately. If you're on *nix, you can try looking at `/etc/timezone`. – Amber Sep 30 '12 at 06:19
  • (See http://stackoverflow.com/questions/3118582/how-do-i-find-the-current-system-timezone for more comments on that particular problem - Python doesn't handle this any better than C++ does.) – Amber Sep 30 '12 at 06:20
  • I ended up using `local_tz = dateutil.tz.tzlocal()` which seems to work well enough. – mankoff Sep 30 '12 at 06:26