Search code examples
python-2.7python-dateutil

parse a date to utc unixtime


a commandline program i am writing accepts dates as arguments. i need to convert these to a utc unix timestamp for internal use within the program. so far i have the following test script, but its not working:

>>> import time
>>> from dateutil import parser
>>> t = parser.parse("2009-01-10")
>>> print int(time.mktime(t.timetuple()))
1231507800

checking this on unixtimestamp.com:

1231507800

Is equivalent to:

01/09/2009 @ 1:30pm (UTC)

however i want it back at midnight. i think my computer is using my local timezone, when i want to use utc at every stage.


Solution

  • You could subtract the date from the epoch and call the timedelta.total_seconds method:

    import datetime as DT
    from dateutil import parser
    datestring = "2009-01-10"
    date = parser.parse(datestring)
    epoch = DT.datetime(1970, 1, 1)
    timestamp = (date - epoch).total_seconds()
    print(timestamp)
    

    prints

    1231545600.0
    

    Another alternative is to use calendar.timegm and datetime.utctimetuple since both of these functions interpret their argument as being in UTC,

    import calendar
    print(calendar.timegm(date.utctimetuple()))
    # 1231545600
    

    but note that date.utctimetuple() drops microseconds.