Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting 'Time' to AM/PM
#9
    if (hr <=12) :
This doesn't make sense to me. 11:22 is AM, but 12:22 is PM. I would have thought you'd check hr < 12

You're repeating your code. And you're checking things the library could tell you. Since both stanzas do the identical conversion, what is the utility of the "if"? I'd probably rewrite it like this:

from datetime import datetime
tms= ['2021-07-05-231403','2021-07-05-221402','2021-07-05-214001','2020-07-05-221400','2021-07-05-121404','2021-07-05-111405','2021-07-05-101406']

for et in tms :
    et=et.strip()
    d = datetime.strptime(et, "%Y-%m-%d-%H%M%S")
    d2 =datetime.strftime(d, "%d/%m/%Y %I:%M:%S %p")
    ampm = datetime.strftime(d, "%p")
    print(f" {ampm} --> {d2}")
No duplicated code, and the AM or PM bit matches what I'd expect (times after noon are PM, not AM).
tester_V likes this post
Reply


Messages In This Thread
Converting 'Time' to AM/PM - by tester_V - Jul-27-2021, 08:58 PM
RE: Converting 'Time' to AM/PM - by bowlofred - Jul-27-2021, 10:01 PM
RE: Converting 'Time' to AM/PM - by tester_V - Jul-28-2021, 06:27 AM
RE: Converting 'Time' to AM/PM - by tester_V - Jul-28-2021, 05:53 PM
RE: Converting 'Time' to AM/PM - by tester_V - Jul-28-2021, 06:10 PM
RE: Converting 'Time' to AM/PM - by Yoriz - Jul-28-2021, 06:17 PM
RE: Converting 'Time' to AM/PM - by tester_V - Jul-28-2021, 06:56 PM
RE: Converting 'Time' to AM/PM - by Yoriz - Jul-28-2021, 07:04 PM
RE: Converting 'Time' to AM/PM - by bowlofred - Jul-28-2021, 07:21 PM
RE: Converting 'Time' to AM/PM - by snippsat - Jul-28-2021, 08:55 PM
RE: Converting 'Time' to AM/PM - by tester_V - Jul-28-2021, 11:51 PM
RE: Converting 'Time' to AM/PM - by snippsat - Jul-29-2021, 05:39 AM
RE: Converting 'Time' to AM/PM - by tester_V - Jul-30-2021, 06:29 AM
RE: Converting 'Time' to AM/PM - by snippsat - Jul-30-2021, 02:00 PM
RE: Converting 'Time' to AM/PM - by tester_V - Jul-30-2021, 05:21 PM
RE: Converting 'Time' to AM/PM - by snippsat - Jul-30-2021, 05:55 PM
RE: Converting 'Time' to AM/PM - by tester_V - Jul-30-2021, 08:18 PM
RE: Converting 'Time' to AM/PM - by snippsat - Jul-30-2021, 08:56 PM
RE: Converting 'Time' to AM/PM - by tester_V - Jul-30-2021, 09:07 PM

Forum Jump:

User Panel Messages

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