'Parsing date time with UTC offset in python 3.6
I run into the problem while parsing datetime from string. I compiled my findings into simple example:
import datetime
# Works in python 3.6 as well as 3.7 and newer
value2 = '2012-12-03T07:16:23+0000'
print(datetime.datetime.strptime(value2, '%Y-%m-%dT%H:%M:%S%z'))
# Works only in python 3.7 and newer
value = '2012-12-03T07:16:23+00:00'
print(datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S%z'))
For some reason python 3.6 cannot parse string containing timezone information in standard form of xx:xx. Does anybody know how to solve this issue?
Solution 1:[1]
I run into the same issue. After debugging found that that 3.6 does not have support for datetime with colon. The work around of the problem there are two solution
- upgrade python version to python3.7. As python 3.7 documentation states here:
utcoffset() is transformed into a string of the form ±HHMM[SS[.ffffff]], where HH is a 2-digit string giving the number of UTC offset hours, MM is a 2-digit string giving the number of UTC offset minutes, SS is a 2-digit string giving the number of UTC offset seconds and ffffff is a 6-digit string giving the number of UTC offset microseconds.
Changed in version 3.7: When the %z directive is provided to the strptime() method, the UTC offsets can have a colon as a separator between hours, minutes and seconds. For example, '+01:00:00' will be parsed as an offset of one hour. In addition, providing 'Z' is identical to '+00:00'.
- apply some hack to remove colon (or whole timezone part if not needed)
2.1. Replace colon with ''
import datetime value = '2012-12-03T07:16:23+00:00' value = value.replace(':', '') print(datetime.datetime.strptime(value, '%Y-%m-%dT%H%M%S%z'))2.2. remove the zone part from date srt
import datetime value = '2012-12-03T07:16:23+00:00' value = value.split('+', maxsplit=1)[0] print(datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S'))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MOHD NAYYAR |
