0

My goal is to convert a tz-aware object to a different timezone. For example - consider the code below where I have a tz-aware object in timezone 'US/Eastern':

import pytz
from datetime import timedelta

datetime_est = datetime(2020, 7, 10, 9, 23, 53, tzinfo=pytz.timezone('US/Eastern'))

The problem is that when I print the timestamp like this: datetime_est.timestamp() (which should be UTC) I get 2020 July 10 14:19:53. This is +5 hours.

Why +5 when the same time in UTC should be +4?

Newskooler
  • 3,973
  • 7
  • 46
  • 84
  • Don't assign the time zone directly. Use the `localize` function. See the answer in the duplicate. This is also one of the very first things in the pytz docs. ;) – Matt Johnson-Pint Jul 10 '20 at 17:24
  • Thank you! Yes the duplicate covers it. I knew it was asked somewhere already and I thought it may be the `localize` but the word `local` kind of sounds not very intuitive for thins kind of thing... Anyway, thanks! – Newskooler Jul 10 '20 at 17:48
  • 1
    FYI - pytz is fine, but the `dateutil` package is more modern and intuitive for this sort of thing. See https://dateutil.readthedocs.io/en/stable/examples.html#tzfile-examples. Also, [PEP-615](https://www.python.org/dev/peps/pep-0615/) adds built-in support to Python for this. It is available in Python 3.9 beta 1 and greater. – Matt Johnson-Pint Jul 10 '20 at 18:22
  • Ideally i would like to not use pytz. I will give the documentation a good read. Thanks. – Newskooler Jul 10 '20 at 18:36
  • Sorry, I pointed at the wrong place. Use `gettz` function, as shown here: https://dateutil.readthedocs.io/en/stable/tz.html#dateutil.tz.gettz The files themselves come from the OS. – Matt Johnson-Pint Jul 10 '20 at 18:50
  • Okay, I read thorough it now, however I don't get how do we apply this to actually change the tz of a datetime object (or is it more accurate to say to view it in a different tz)? – Newskooler Jul 10 '20 at 19:55
  • Actually I think I figured how to do that, so more the question now is (compared to `pytz`) how do I `localize` with `dateutil.tz` before I add the time zone? – Newskooler Jul 10 '20 at 20:04

0 Answers0