I am trying to parse and extract values from my time data 2018-03-11 13:15:31.734874+01:00
.
I'm using strptime()
to do this with the %Y %m %d %H:%M:%S.%f %Z
format but I am getting this error:
ValueError: time data '2018-03-11 13:15:31.734874+01:00' does not match format '%Y %m %d %H:%M:%S.%f %Z'
Also, I don't know how to handle the +1:00
in my time data. Can anyone help?
There are two problems here to solve.
First is the format string. It should be %Y-%m-%d %H:%M:%S.%f%z
to match exact date separators and timezone sequence (without space).
From strftime and strptime Behavior:
%z
(lower case) UTC offset in the form +HHMM or -HHMM (empty string if the object is naive). (empty), +0000, -0400, +1030
Second is the colon (:) in timezone offset '+01:00'. That can be left out using substring: s[:-3]+s[-2:] or string substitute.
So the final answer is as below.
from datetime import datetime
s = '2018-03-11 13:15:31.734874+01:00'
datetime.strptime(s[:-3]+s[-2:], '%Y-%m-%d %H:%M:%S.%f%z')