简体   繁体   中英

ValueError: '2' is a bad directive in format '%Y-%m-%d%20%H:%M:%S'

I am trying to get data from an API that sends the time like "2022-08-15%2013:00:00" in string format, How do I convert it into a datetime format? I have tried -

start_time = "2022-08-15%2013:00:00"
start_dt_obj = datetime.strptime( str(start_time), r'%Y-%m-%d%20%H:%M:%S')

But this gives an error -

ValueError: '2' is a bad directive in format '%Y-%m-%d%20%H:%M:%S'

How do I resolve this?

%20 is an URL encoded space character, so 2022-08-15%2013:00:00 should be in fact interpreted as 2022-08-15 13:00:00 . You can achieve that using urllib.parse.unquote

import datetime
from urllib.parse import unquote

start_time = "2022-08-15%2013:00:00"

start_dt_obj = datetime.datetime.strptime(unquote(start_time), r'%Y-%m-%d %H:%M:%S')
print(start_dt_obj)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM