Python: how to handle timestamps (ISO8601)

I need to deal with python with strings representing iso8601 timestamps.

Therefore, the timestamp line is as follows:

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

I am currently converting them to python using:

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

But in this way I lose all the time zone information. I saw many examples here about so about timestamps and python, unfortunately, no one saved the time zone, but simply restored the time zone delay using:

delay = timestamp[-6:]

I also tried:

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

but he returned

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

Can you give some idea?

+5
source share
2 answers

python iso8601 parse_date, :

>>> 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'>)

, astimezone (tz)

UTC datetime, utctimetuple().

+2

, ; pytz .

, pytz, , zc.iso8601 iso8601, :

from zc.iso8601.parse import datetimetz
datetimetz(timestamp)
+1

All Articles