Search code examples
pythondjangopython-2.7datetimedjango-1.9

Python utcfromtimestamp and fromtimestamp output same value?


I have a Python+Django app which stores everything in UTC, and has TIME_ZONE = 'UTC' and USE_TZ = True in the settings. When converting a POSIX timestamp I get the same output from both flavors of fromtimestamp:

start_seconds = 1461798000000 / 1000.0

start = datetime.datetime.utcfromtimestamp(start_seconds)
print('With utc: %s' % start)
>>>> With utc: 2016-04-27 23:00:00

start2 = datetime.datetime.fromtimestamp(start_seconds)
print('Without utc: %s' % start2)
>>>> Without utc: 2016-04-27 23:00:00

Why would this be?


Solution

  • if fromtimestamp() and ucfromtimestamp() return the same value then it means the local time zone has a zero utc offset at the given time. Django sets your local timezone (TZ envvar), to reflect the TIME_ZONE setting that is UTC in your case and (obviously) the utc offset is zero in UTC.

    To get a timezone-aware datetime object that corresponds to a given POSIX timestamp:

    from datetime import datetime, timedelta
    import pytz
    
    dt = datetime(1970, 1, 1, tzinfo=pytz.utc) + timedelta(seconds=start_seconds)
    

    To convert Unix time:

    dt = datetime.fromtimestamp(start_seconds, pytz.utc)
    

    The values may differ in edge cases.