0

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.

Community
  • 1
  • 1
mulllhausen
  • 4,225
  • 7
  • 49
  • 71
  • related: [Converting datetime.date to UTC timestamp in Python](http://stackoverflow.com/q/8777753/4279) – jfs Jul 18 '15 at 19:38

1 Answers1

1

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.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • i guess this indicates that `parser.parse` was correct and it must have been `time.mktime` that was converting for my timezone instead of using utc. – mulllhausen Jul 18 '15 at 14:17
  • 1
    Yes, `time.mktime` interprets its argument as a local timetuple. `calendar.timegm` interprets its argument as a UTC timetuple. You could use `calendar.timegm(t.utctimetuple())`, but `utctimetuple` drops microseconds, while the method above does not. – unutbu Jul 18 '15 at 14:25