3

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

3
  • which python version are you using? if you're using 2.7 its not going to work if I remember correctly, had the issue before. Commented May 2, 2018 at 10:58
  • I am using python 3 Commented May 2, 2018 at 11:01
  • The issue is the ':' on your offset if you remove this then it works Commented May 2, 2018 at 11:01

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I will try it, but why does postgreSQL save it with the colon, I need some workaround code now to replace it everytime. That is really weird.
No idea I don't use it, you may have better luck if the dtype stored in your database is an actual datetime type and just load directly from the db in which case the dtype will be inferred but I can't tell you as I have no expertise in that
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.