0

How do I modify the code below to handle a timezone, note there is no decimal.

2015-12-22T11:57:11-08:00, -8:00 is causing me issues, does epoch time take time zone into account?

timegm(datetime.strptime(datestring, "%Y-%m-%dT%H:%M:%S.%f").timetuple())
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Bob R
  • 605
  • 1
  • 13
  • 25

1 Answers1

0

There are a few issues here.

  1. If your time doesn't include a microsecond block, this date string will not work with the format string you provided. Just try it without the -08:00 bit. That means you either need to assume that all your times won't have that block or you need to account for both possibilities.
  2. strptime does a TERRIBLE job of dealing with ISO8601 offsets. If you look at the formatting guide, you'll notice that you can use %z for +/-HHMM, but ISO8601 time zones (in my experience) are almost always presented with the format +/-HH:MM. And even then %z has a nasty habit of being called a bad directive in the format string.

To answer your question, yes, time zone matters. The UNIX epoch is seconds since 1970-01-01T00:00:00+00:00. More importantly, even if you correctly assign the datetime object's tzinfo when you parse the string, timetuple will NOT take into account that tzinfo. You need to use utctimetuple

So now you just need to properly parse the datetime. There are solutions that don't use external libraries, but I find the easiest way to parse ISO8601 date strings is to use the python-dateutil package available via pip:

>>> import calendar
>>> from dateutil import parser
>>> datestring = '2015-12-22T11:57:11-08:00'
>>> tz_aware_datetime = parser.parse(datestring)
>>> tz_aware_datetime
datetime.datetime(2015, 12, 22, 11, 57, 11, tzinfo=tzoffset(None, -28800))
>>> calendar.timegm(tz_aware_datetime.utctimetuple())
1450814231
James J.
  • 216
  • 1
  • 5