Search code examples
pythontimetimezone

Does Python's time.time() return the local or UTC timestamp?


Does time.time() in the Python time module return the system's time or the time in UTC?


Solution

  • The time.time() function returns the number of seconds since the epoch, as a float. Note that “the epoch” is defined as the start of January 1st, 1970 in UTC. So the epoch is defined in terms of UTC and establishes a global moment in time. No matter where on Earth you are, “seconds past epoch” (time.time()) returns the same value at the same moment.

    Here is some sample output I ran on my computer, converting it to a string as well.

    >>> import time
    >>> ts = time.time()
    >>> ts
    1355563265.81
    >>> import datetime
    >>> datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    '2012-12-15 01:21:05'
    >>>
    

    The ts variable is the time returned in seconds. I then converted it to a human-readable string using the datetime library.