Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 strptime from ISO8601 with timezone

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.

like image 995
yerassyl Avatar asked Feb 28 '26 10:02

yerassyl


1 Answers

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))
like image 157
AKS Avatar answered Mar 03 '26 00:03

AKS