Python Forum

Full Version: Formatting DateTime string and and converting it from AM/PM to 24 hours
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Greetings!
Here are two snippets, it seems both are right but only first one is working:
I'm confused why the second one is not working:
dt_str2 = "2024-06-01  08:20:00 PM"
dt_object = datetime.strptime(dt_str2, "%Y-%m-%d %I:%M:%S %p").strftime("%m/%d/%Y %H:%M:%S")
print(f" == {dt_object} == {type(dt_object)}")
'''
        Converting 6/1/2024 11:05:40 PM to 2024-06-01 23:05:40
'''
dt_str3 = "6/1/2024 11:05:40 PM "
dt_ob3 = datetime.strptime(dt_str3, "%m/%d/%Y %I:%M:%S %p").strftime("%Y-%m-%d %H:%M:%S")
print(f" == {dt_ob3} == {type(dt_ob3)}")
Thank you.
You have an extra space in "6/1/2024 11:05:40 PM ". The space is not accounted for in your strptime format.
You are right! Thank you! Big Grin