Python Forum
Formatting DateTime string and and converting it from AM/PM to 24 hours
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Formatting DateTime string and and converting it from AM/PM to 24 hours
#1
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.
Reply
#2
You have an extra space in "6/1/2024 11:05:40 PM ". The space is not accounted for in your strptime format.
tester_V likes this post
Reply
#3
You are right! Thank you! Big Grin
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  subtract 2 datetime string jss 4 979 Oct-19-2023, 02:42 PM
Last Post: Larz60+
  Formatting a date time string read from a csv file DosAtPython 5 1,616 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  String formatting (strptime) issues Henrio 2 963 Jan-06-2023, 06:57 PM
Last Post: deanhystad
  MatplotibTicks every 24 hours TamP 4 1,295 Oct-04-2022, 04:08 PM
Last Post: deanhystad
  Hello all! need help. calculating OT hours. no1up 5 1,652 Jul-30-2022, 10:00 PM
Last Post: rob101
  Converting '1a2b3c' string to Dictionary PythonNoobLvl1 6 2,023 May-13-2022, 03:44 PM
Last Post: deanhystad
  confused about string formatting barryjo 7 2,122 Mar-06-2022, 02:03 AM
Last Post: snippsat
  string formatting barryjo 7 2,235 Jan-02-2022, 02:08 AM
Last Post: snippsat
  Help with string formatting in classes brthurr 6 12,163 Dec-17-2021, 04:35 PM
Last Post: Jeff900
  Need help converting string to int dedesssse 7 2,850 Jul-07-2021, 09:32 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020