M.E.
M.E.

Reputation: 5496

pytz US/Eastern converting timestamps back and forth

From time and date website:

Generalized Time Zone in New York
ET  Eastern Time    UTC -5:00 / -4:00   Wed, 11:42:33

Time Zone Currently Being Used in New York
UTC -5  EST Eastern Standard Time   New York    Wed, 11:42:33

Time Zone Not Currently Being Observed in New York
UTC -4  EDT Eastern Daylight Time   10 Mar 2019

So basically New York time is EST or EDT depending on which period of the year we are currently on due to the DayLight timesaving.

When using US/Eastern in pytz, does it refer to ET, EST or EDT?. Does it take into consideration the EST/EDT time change?

I am using this code to get timestamps for the beginning and end of the day of a given date in Eastern Time:

    import datetime
    import pytz

    session = datetime.datetime.strptime('26/02/2019', '%d/%m/%Y')
    exchange_tz = pytz.timezone('US/Eastern')
    session_localized = exchange_tz.localize(session)

    _period1 = int((session_localized - datetime.datetime(1970, 1, 1, tzinfo=exchange_tz)).total_seconds())
    _period2 = int((session_localized - datetime.datetime(1970, 1, 1, tzinfo=exchange_tz)).total_seconds()) + 24*60*60

    >>> _period1
    1551139200
    >>> _period2
    1551225600

I am not 100% sure that those timestamps have been properly generated. Because when I try to convert them back to localized datetimes I get 1 hour of difference:

    _exchange_tz = pytz.timezone('US/Eastern')
    _exchange_ts = _exchange_tz.localize( datetime.datetime.fromtimestamp(1551139200) )

    >>> str(_exchange_ts)
    '2019-02-26 01:00:00-05:00'

Which as far as I understand, it shall be 2019-02-26 00:00:00. What am I doing wrong?

I have also read in pytz documentation that normalize() function shall be used when doing arithmetics covering, but I am not sure if this apply to this case or not.

Upvotes: 2

Views: 3714

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241420

When using US/Eastern in pytz, does it refer to ET, EST or EDT?. Does it take into consideration the EST/EDT time change?

These are IANA (aka TZDB, Olson, etc.) time zone identifiers. US/Eastern is a link/alias to America/New_York. Both correctly model the history of the US Eastern time zone, including EST or EDT depending on when they are applicable.

Regarding your example, the timestamp 1551139200 equates to 2019-02-26T00:00:00Z (UTC). In US Eastern Time, that's 2019-02-25T19:00:00-05:00. That should be the result you get. You would first need to localize the input value to UTC (or in the case of UTC, you can assign tzinfo=pytz.utc safely). Then use the astimezone function to convert to US/Eastern.

Upvotes: 3

Related Questions