Search code examples
pythondatetimeutc

Get UNIX timestamp (ie UTC timestamp) from a Python timezone aware date


My computer is running in Pacific time (hence datetime.datetime.fromtimestamp(0) gives me 1969-12-31 16:00:00). My problem is that given a timezone aware datetime object in Python, I want to get the UNIX timestamp (ie the UTC timestamp). What is the best way to do so?


Solution

  • import calendar
    import datetime
    import pytz
    
    d = datetime.datetime.now(pytz.timezone('America/Los_Angeles'))
    # d == datetime.datetime(2012, 7, 10, 1, 6, 36, 37542, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
    
    ts = calendar.timegm(d.utctimetuple())
    # ts == 1341907596
    
    # test with UTC epoch:
    
    d = datetime.datetime(1969, 12, 31, 16, 0, 0, 0, pytz.timezone('America/Los_Angeles'))
    # d == datetime.datetime(1969, 12, 31, 16, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
    
    ts = calendar.timegm(d.utctimetuple())
    # ts == 0