UTC time conversion to internal time

Fredrik Lundh fredrik at pythonware.com
Wed Feb 13 11:19:24 EST 2002


Colin Brown wrote:

> I wish to convert UTC times to internal time representation (the inverse of
> time.gmtime). There does not seem to be any function to do this. Does anyone
> have a clean solution please.

in recent Python versions, you can use calendar.timegm:

>>> import calendar
>>> help(calendar.timegm)
Help on function timegm in module calendar:

timegm(tuple)
    Unrelated but handy function to calculate Unix timestamp from GMT.

:::

if it's not available in your Python version, you can use this one instead:

# time-example-4.py
# from O'Reilly's "Python Standard Library"

import time

def _d(y, m, d, days=(0,31,59,90,120,151,181,212,243,273,304,334,365)):
    # map a date to the number of days from a reference point
    return (((y - 1901)*1461)/4 + days[m-1] + d +
        ((m > 2 and not y % 4 and (y % 100 or not y % 400)) and 1))

def timegm(tm, epoch=_d(1970,1,1)):
    year, month, day, h, m, s = tm[:6]
    assert year >= 1970
    assert 1 <= month <= 12
    return (_d(year, month, day) - epoch)*86400 + h*3600 + m*60 + s


</F>

<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list