0

Now that it's daylight savings time in my timezone, I'm having a problem translating UTC to local time.

>>> from dateutil.parser import parse
>>> from dateutil import tz
>>> dt = parse('1:30').replace(tzinfo=tz.tzutc())
>>> dt
datetime.datetime(2015, 3, 8, 1, 30, tzinfo=tzutc())
>>> dt = dt.astimezone(tz.tzlocal())
>>> dt
datetime.datetime(2015, 3, 7, 20, 30, tzinfo=tzlocal())

When it's 1:30 UTC it's 21:30 local time, but I'm getting 20:30, which would be correct if we hadn't changed to DST this morning.

I have the feeling I'm missing something obvious.

foosion
  • 7,619
  • 25
  • 65
  • 102
  • It's not DST yet (in most locations of the world), my guess is that your location might not be set correctly. Most of the countries that use DST switch the last sunday of march. In other words, please show what your `tzlocal()` is giving you, it's most likely wrong :) – Wolph Mar 09 '15 at 01:55
  • @Wolph it gives 'Eastern Daylight Time' which is correct. Determined with `datetime.now(tz.tzlocal()).tzname()` – foosion Mar 09 '15 at 02:01
  • It's hard to reproduce this problem since other people who run your code will get different values for `tzlocal`. It seems to work for me in Pacific Daylight Time. What do you get if you `import datetime` and then do `datetime.datetime.now(tz.tzutc()).astimezone(tz.tzlocal())`? Do you get the correct local time? – BrenBarn Mar 09 '15 at 02:08
  • @BrenBarn that gets the correct time, 22:11 at the moment. Why should that work and what I do in the Q not work? – foosion Mar 09 '15 at 02:12
  • But does it contain DST info? Anyhow, I would recommend using the `pytz` library for the correct timezone. For example: `import pytz; print pytz.timezone('America/Los_Angeles')` returns: `` – Wolph Mar 09 '15 at 02:16
  • note: [`dateutil.tz.tzlocal()` may fail; use `pytz` if you are not sure](http://stackoverflow.com/a/17365806/4279) – jfs Mar 09 '15 at 02:58

1 Answers1

2

I think I see the problem. You began with the UTC time 1:30 on March 8. This corresponds to a time in Eastern Time before daylight savings took effect, since daylight savings takes effect at 2am local time on March 8. Try using a later UTC time for your test and it should work.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384