6

I have to deal in python with strings representing iso8601 timestamps.

My timestamps string are therefore in the following form:

timestamp = "2011-08-18T10:29:47+03:00"

Currently I'm converting them in python using:

timestamp = timestamp[:-6]
timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S")

But in this way I lose all the information about the time zone. I have seen many examples here on s-o about timestamps and python, unfortunately no one was preserving the timezone as well, or just recover the time zone delay using:

delay = timestamp[-6:]

I have also tried:

timestamp = "2011-08-18T10:29:47+03:00"
timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S%z")

but it returned

ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S%z'

Can you give some insight?

user601836
  • 3,215
  • 4
  • 38
  • 48
  • you might mean [Internet Date/Time Format described in rfc 3339 (a profile of iso 8601)](http://tools.ietf.org/html/rfc3339#section-5.6) – jfs Aug 20 '14 at 09:28
  • related: [ISO to datetime object: 'z' is a bad directive](http://stackoverflow.com/q/20194496/4279) – jfs Jan 08 '15 at 07:20

2 Answers2

3

The python iso8601 module is built with a wonderful parse_date method that can handle timezone info :

>>> import iso8601
>>> iso8601.parse_date("2007-01-25T12:00:00Z")
datetime.datetime(2007, 1, 25, 12, 0, tzinfo=<iso8601.iso8601.Utc ...>)

>>> iso8601.parse_date("2011-08-18T10:29:47+03:00")
datetime.datetime(2011, 8, 18, 10, 29, 47, tzinfo=<FixedOffset '+03:00'>)

If you want to convert it in another timezone, use the astimezone(tz) method

If you need to get the UTC datetime you can use the utctimetuple() method.

Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
1

You'll need to add an external module that provides timezone support; the pytz module provides you with the necessary timezone database.

You'll either need to parse the timezone by hand to construct a pytz timezone, or use a package like zc.iso8601 or iso8601 to do the parsing for you:

from zc.iso8601.parse import datetimetz
datetimetz(timestamp)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343