Skip to content
Advertisement

Python print the same timestamp the same anywhere

I’m given a timestamp in seconds, and I ‘inherited’ a function to print it in human-readable form, but the function is locale-specific; that is, it matters what time zone the host is configured for. I want to print that time as GMT no matter what time zone I’m in. For example, here’s the sequence on a computer in Mountain Time (the value 315878400 is a ‘magic number’):

>>> import time
>>> secs = 1308512779
>>> tmp = secs + 315878400
>>> print(time.ctime(tmp))
Tue Jun 22 13:46:19 2021

And here it is on a computer in Pacific Time:

>>> import time
>>> secs = 1308512779
>>> tmp = secs + 315878400
>>> print(time.ctime(tmp))
Tue Jun 22 12:46:19 2021

Given the same time in seconds I’d like to run the same code anywhere and get the same string for output. Since I don’t control the source of the seconds data itself, it’s acceptable to assume it’s GMT. Everything I find on the Web is about how to get my local time now, and that’s not what this is about. Any help would be appreciated.

Advertisement

Answer

It sounds like you are describing Unix time. Python makes it very easy to get datetime objects from Unix time!

from datetime import datetime

def convert(timestamp):
    return datetime.utcfromtimestamp(timestamp)

print(convert(1308512779))
# prints: 2011-06-19 19:46:19
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement