0-23 hour military clock to standard time (hh:mm)
18,855
Solution 1
Split the input by :
, and use formatted output in the end:
def timeConvert():
miliTime = input("Enter a time in hh:mm (military) format: ")
hours, minutes = miliTime.split(":")
hours, minutes = int(hours), int(minutes)
setting = "AM"
if hours > 12:
setting = "PM"
hours -= 12
print(("%02d:%02d" + setting) % (hours, minutes))
Solution 2
Use the datetime module's strptime()
to read the string as a datetime object and then convert it back to string using strftime()
, example -
>>> datetime.datetime.strptime('3:5','%H:%M').strftime('%I:%M %p')
'03:05 AM'
>>> datetime.datetime.strptime('18:30','%H:%M').strftime('%I:%M %p')
'06:30 PM'
>>> datetime.datetime.strptime('00:00','%H:%M').strftime('%I:%M %p')
'12:00 AM'
The formats explained -
%H - Hour (24-hour fomrat)
%M - Minute
%I - Hour (12-hour format)
%p - AM or PM
Function would look like -
def timeConvert():
import datetime
ds = input("Enter a time in hh:mm (military) format: ")
newds = datetime.datetime.strptime(ds, ,'%H:%M').strftime('%I:%M %p')
print(newds)
Author by
Admin
Updated on July 03, 2022Comments
-
Admin almost 2 years
How would I go about this process? Let's say that someone types in "3:5", and I should be able to get the output "3:05 AM". Or if someone types in "00:00", I should get "12:00 AM". I realize the plethora of ways to go about this if the time format was simply input as "hhmm", but the input can range from "h:m", "hh:m", "hh:m", and "hh:mm". So it's very situational.
def timeConvert(): miliTime = int(input("Enter a time in hh:mm (military) format: ")) miliTime.split(":") if len(miliTime) == 3: hours = miliTime[0] minutes = miliTime[2] if hours < 0: print("Hours can't be less than 0.") elif len(miliTime) == 4: if miliTime[0:2] >= 10: hours = militime[0:2] minutes = militime[3] if minutes < 0: print("Minutes can't be less than 0.") if minutes < 10: minutes = 0 + minutes else: hours = miliTime[0] minutes = militime[2:] if minutes >= 60: print("Too big of a number for minutes.") else: hours = miliTime[0:2] minutes = miliTime[3:] setting = AM if hours > 12: setting = PM hours -= 12 print(hours + ":" + minutes + setting) timeConvert()