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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With