3

How to convert string in ISO8601 time format to python3 datetime. Here is my time:

2017-03-03T11:30:00+04:00

And the way I try:

datetime.strptime(appointment['datetime'], '%Y-%m-%dT%H:%M:%S%z')

The problem here, is that I don't know how to represent +4:00 timezone in format parameter of .strptime method.

yerassyl
  • 2,958
  • 6
  • 42
  • 68
  • please refer this link http://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date . I think this will be helpful parser class of dateutil library of python will do fine. – Anand Tripathi Mar 03 '17 at 05:53

1 Answers1

6

Notice that %z in python datetime doesn't include a colon:

%z: UTC offset in the form +HHMM or -HHMM (empty string if the object is naive) e.g. +0000, -0400, +1030

However, the date string in the example does have a colon e.g. +04:00. Just by not including that colon you can parse the date.

>>> s = "2017-03-03T11:30:00+04:00"
>>> datetime.strptime(s[:len(s)-3] + s[len(s)-2:], '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2017, 3, 3, 11, 30, tzinfo=datetime.timezone(datetime.timedelta(0, 14400)))

I would suggest that you use this powerful library python-dateutil:

>>> from dateutil import parser
>>> parser.parse("2017-03-03T11:30:00+04:00")
datetime.datetime(2017, 3, 3, 11, 30, tzinfo=tzoffset(None, 14400))
AKS
  • 18,983
  • 3
  • 43
  • 54
  • `dateutil.parser` is too wide, such as `parse("Thu, 25 Sep 2003 10:49:41 -0300")` can also work. How to limit the format of the time only to ISO-8601 with timezone? – Cloud Aug 08 '18 at 06:20