One may ask, why add an answer if there are already relevant ones?
Well, I realized that some questions have been closed without actually getting an accurate solution so I chose to add this solution for OPs who are looking to accomplish same results using only logic and avoiding any import
. such as This OP
def convert_time(time_string):
hours, minutes = map(int, time_string.split(":"))
meridian = "AM"
if hours > 12:
hours -= 12
meridian = "PM"
elif hours == 12:
meridian = "PM"
elif hours == 0:
hours = 12
return f"{hours:02}:{minutes:02} {meridian}"
# Call the function:
time_dict = {'Wed': '10:30 - 21:00', 'Sun': '10:30 - 21:00', 'Thu': '10:30 - 21:00',
'Mon': '10:30 - 21:00', 'Fri': '10:30 - 22:00', 'Tue': '10:30 - 21:00',
'Sat': '10:30 - 22:00'}
for day, hours in time_dict.items():
start_time, end_time = map(lambda x: x.strip(), hours.split("-"))
time_dict[day] = f"{convert_time(start_time)} - {convert_time(end_time)}"
print(time_dict)
{'Wed': '10:30 AM - 09:00 PM', 'Sun': '10:30 AM - 09:00 PM',
'Thu': '10:30 AM - 09:00 PM', 'Mon': '10:30 AM - 09:00 PM',
'Fri': '10:30 AM - 10:00 PM', 'Tue': '10:30 AM - 09:00 PM',
'Sat': '10:30 AM - 10:00 PM'}
If your time input is a string
like "00:29"
, just go ahead and call the function:
str_time_input = "00:29"
print(convert_time(str_time_input)) # 12:29 AM
What if you have both hours and minutes as int
?:
hours = 12
minutes = 17
str_time = f"{hours}:{minutes}"
print(type(str_time))
print(convert_time(str_time))
<class 'str'>
12:17 PM