Roman
Roman

Reputation: 3941

Python strptime ValueError: time data does not match format

I have added timezones to my datetime column in my postgreSQL DB.

Now I have the error above everytime I want to compare dates. On some points I have JSON requests, datetime objects are passed as strings, so I need to parse them, with the additonal timezone info I get:

ValueError: time data '2018-05-02 11:52:26.108540+02:00' 
does not match format '%Y-%m-%d %H:%M:%S.%f+%Z' 

Earlier I had:

2018-05-02 11:52:26.108540

which worked perfectly with:

%Y-%m-%d %H:%M:%S.%f

The new information which has been added is: +02:00

In the strptime docu it is telling me to use %z or %Z but it does not work.

EDIT:

I am using Python 3

Upvotes: 3

Views: 3894

Answers (2)

MrLeeh
MrLeeh

Reputation: 5589

You need to remove the colon and use the small %z for this to work.

>>> s = '2018-05-02 11:52:26.108540+02:00'
>>> fmt = %Y-%m-%d %H:%M:%S.%f%z'
>>> time.strptime(s, fmt)
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=2, tm_hour=11, tm_min=52, tm_sec=26, tm_wday=2, tm_yday=122, tm_isdst=-1)

Upvotes: 1

EdChum
EdChum

Reputation: 394399

The issue is the offset +02:00 you need to remove the colon ':' then it will work:

In[48]:
dt.datetime.strptime('2018-05-02 11:52:26.108540+0200', '%Y-%m-%d %H:%M:%S.%f%z')

Out[48]: datetime.datetime(2018, 5, 2, 11, 52, 26, 108540, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))

So you would need to go through all your datetime strings and remove this in order for strptime to parse it correctly

Upvotes: 4

Related Questions