Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting 'Time' to AM/PM
#1
Greetings to all!
I'm sure I'm trying to invent a bicycle.
I need to convert strings in the following format to AM/PM:
st = '2021-07-05-231403'
I wrote a small snipped and it does what I want but ti looks crude, there is no elegance in it.
st = '2021-07-05-221403'
ya,mo,da,hms =st.split("-")
print(f" HMS -> {hms}")
hh=hms[:2]
mm=hms[2:4]
ss=hms[4:6]
hh=int(hh)
print(f" Hours ---> {hh}")
print(f" Minutes -> {mm}")
print(f" Seconds -> {ss}")
if hh == 23 :
    hh=11
    print(f" {hh}:PM") # <- Converted to PM
    hh=str(hh)
    out=mm+"/"+da+"/"+ya+" "+hh+":"+mm+":"+ss+" "+"PM"
    print(f" Converted to AM/PM -> {out}")
if hh == 22 :
    hh=10
    print(f" {hh}:PM") # <- Converted to PM
    hh=str(hh)
    out=mm+"/"+da+"/"+ya+" "+hh+":"+mm+":"+ss+" "+"PM"
    print(f" Converted to AM/PM -> {out}")  
Thank you!
Reply
#2
For anything real, please use a time library to print it in the format you want.

from datetime import datetime

st = '2021-07-05-231403'

d = datetime.strptime(st, "%Y-%m-%d-%H%M%S")
print(d)
print(datetime.strftime(d, "%Y-%m-%d %I:%M:%S %p"))
Output:
2021-07-05 23:14:03 2021-07-05 11:14:03 PM
If you're just looking at it as an exercise, then you're already doing all the work to parse out the hour. All you need to do then is map different hours to AM/PM

all_hours = range(24)

def hour24_to_ampm(hour):
    ampm = "AM" if hour < 12 else "PM"
    new_hour = (hour - 1) % 12 + 1
    return new_hour, ampm

for hour in all_hours:
    new_hour, ampm = hour24_to_ampm(hour)
    print(f"{hour} -> {new_hour} {ampm}")
Output:
0 -> 12 AM 1 -> 1 AM 2 -> 2 AM 3 -> 3 AM 4 -> 4 AM 5 -> 5 AM 6 -> 6 AM 7 -> 7 AM 8 -> 8 AM 9 -> 9 AM 10 -> 10 AM 11 -> 11 AM 12 -> 12 PM 13 -> 1 PM 14 -> 2 PM 15 -> 3 PM 16 -> 4 PM 17 -> 5 PM 18 -> 6 PM 19 -> 7 PM 20 -> 8 PM 21 -> 9 PM 22 -> 10 PM 23 -> 11 PM
tester_V likes this post
Reply
#3
bowlofred! You are DA MAN!
It is not an exercise, I'm trying to process log files and they all have different times, 24hours, AM/PM...
I love the first one, formating the sting it looks great!
Thank you!
Reply
#4
I found a problem.
The time strings are always converted to PM times, regardless if it is less or more than 12.
I tried to compare it against "12" but the code fails.

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-131405','2021-07-05-141406']

for et in tms :
    et=et.strip()

    hr = int(et[11:13])
    #print(hr)
    if hr <12 :
        print(f" AM - {hr}")
        d = datetime.strptime(et, "%Y-%m-%d-%H%M%S")
        print(d)
        d2 =(datetime.strftime(d, "%d/%m/%Y %I:%M:%S %p"))
        print(f" AM --> {d2}") 

    if hr >12 :
        print(f" PM - {hr}")
        d = datetime.strptime(et, "%Y-%m-%d-%H%M%S")
        print(d)
        d2 =(datetime.strftime(d, "%d/%m/%Y %I:%M:%S %p"))
        print(f" PM --> {d2}") 
Reply
#5
My bad!
The time strings list has a bad format .
Sorry about that!
I made changes it seems it is forking now.
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()
    hr = int(et[11:13])

    if (hr <=12) :
        #print(f" AM - {hr}")       
        d = datetime.strptime(et, "%Y-%m-%d-%H%M%S")
        d2 =(datetime.strftime(d, "%d/%m/%Y %I:%M:%S %p"))
        print(f" AM --> {d2}") 

    if (hr >12) :
        #print(f" PM - {hr}")
        d = datetime.strptime(et, "%Y-%m-%d-%H%M%S")
        d2 =(datetime.strftime(d, "%d/%m/%Y %I:%M:%S %p"))
        print(f" PM --> {d2}") 
Reply
#6
None of the times in the list are below 12.
Also, 12 will not be included only above or below 12.
tester_V likes this post
Reply
#7
what do you mean?
I'm confused now.
The last three elements of the list are = or less than 12:
'2021-07-05-121404','2021-07-05-111405','2021-07-05-101406'
Reply
#8
They weren't on the post I was replying to, I got delayed in making the post, in the meantime, you had posted again Tongue
tester_V likes this post
Reply
#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
#10
Pendulum is cool bye fair the best date library for Python,i use it always if have deal with timezones.
import pendulum

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:
    dt = pendulum.parse(et, strict=False)
    print(dt.format('DD/MM/YYYY hh:mm:ss A'))
    #print(dt.to_day_datetime_string())
    #print(dt.to_cookie_string())
Output:
05/07/2021 11:14:03 PM 05/07/2021 10:14:02 PM 05/07/2021 09:40:01 PM 05/07/2020 10:14:00 PM 05/07/2021 12:14:04 PM 05/07/2021 11:14:05 AM 05/07/2021 10:14:06 AM ------ Mon, Jul 5, 2021 11:14 PM Mon, Jul 5, 2021 10:14 PM Mon, Jul 5, 2021 9:40 PM Sun, Jul 5, 2020 10:14 PM Mon, Jul 5, 2021 12:14 PM Mon, Jul 5, 2021 11:14 AM Mon, Jul 5, 2021 10:14 AM ------ Monday, 05-Jul-2021 23:14:03 UTC Monday, 05-Jul-2021 22:14:02 UTC Monday, 05-Jul-2021 21:40:01 UTC Sunday, 05-Jul-2020 22:14:00 UTC Monday, 05-Jul-2021 12:14:04 UTC Monday, 05-Jul-2021 11:14:05 UTC Monday, 05-Jul-2021 10:14:06 UTC
Pedroski55 and tester_V like this post
Reply


Forum Jump:

User Panel Messages

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