Search code examples
pythondatetimetimezonepytz

Why does Convertingt EST datetime object to UTC unix timestamp and back to EST add 5 hours?


Why does calling thee below 2 functions on dt result in adding 5 hours? I figured it would remain the same.

from datetime import datetime, time, timedelta
from pytz import timezone

def est_datetime_to_utc_timestamp(dt):
    dt_utc = dt.astimezone(timezone('UTC'))
    ts = int(dt_utc.strftime("%s"))
    return ts

def utc_timestamp_to_est_datetime(ts):
    dt = datetime.fromtimestamp(ts, timezone('UTC'))
    dt = dt.astimezone(timezone('America/New_York'))
    return dt

dt = timezone('America/New_York').localize(datetime(2017, 11, 27, 0, 0))

utc_timestamp_to_est_datetime(est_datetime_to_utc_timestamp(dt))

> datetime.datetime(2017, 11, 27, 5, 0, tzinfo=<DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>)

Solution

  • strftime("%s") is not defined in every implementation.

    Replacing it with .timestamp() works for Python 3.3+, and gives the correct result.

    Alternatively, you can use (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds() if not on Python 3.3+.