Search code examples
pythondatetimeepochpython-datetime

In Python, how to get a localized timestamp with only the datetime package?


I have a unix timestamp in seconds (such as 1294778181) that I can convert to UTC using

from datetime import datetime
datetime.utcfromtimestamp(unix_timestamp)

Problem is, I would like to get the corresponding time in 'US/Eastern' (considering any DST) and I cannot use pytz and other utilities.

Only datetime is available to me.

Is that possible? Thanks!


Solution

  • Easiest, but not supersmart solution is using timedelta

    import datetime
    >>> now = datetime.datetime.utcnow()
    

    US/Eastern is 5 hours behind UTC, so let's just create thouse five hours as a timedelta object and make it negative, so that when reading back our code we can see that the offset is -5 and that there's no magic to deciding when to add and when to subtract timezone offset

    >>> eastern_offset = -(datetime.timedelta(hours=5))
    >>> eastern = now + eastern_offset
    >>> now
    datetime.datetime(2016, 8, 26, 20, 7, 12, 375841)
    >>> eastern
    datetime.datetime(2016, 8, 26, 15, 7, 12, 375841)
    

    If we wanted to fix DST, we'd run the datetime through smoething like this (not entirely accurate, timezones are not my expertise (googling a bit now it changes each year, yuck))

    if now.month > 2 and now.month < 12:
        if (now.month == 3 and now.day > 12) or (now.month == 11 and now.day < 5):
            eastern.offset(datetime.timedelta(hours=5))
    

    You could go even into more detail, add hours, find out how exactly it changes each year... I'm not going to go through all that :)