Skip to content

Instantly share code, notes, and snippets.

@amirsinaa
Last active March 16, 2024 05:58
Show Gist options
  • Save amirsinaa/b63fc8d5f08b729cf795e7b499ffa32c to your computer and use it in GitHub Desktop.
Save amirsinaa/b63fc8d5f08b729cf795e7b499ffa32c to your computer and use it in GitHub Desktop.
Python code that converts time in am,pm to 24H format and 24H to am,pm
def format_ampm_to_24H(time_str):
time_parts = time_str.lower().strip().split()
try:
hours, minutes = map(int, time_parts[0].split(":"))
except ValueError:
return "Invalid input!"
if len(time_parts) == 2:
meridian = time_parts[1].lower()
if meridian == "a.m.":
if hours == 12:
hours = 0
elif meridian == "p.m.":
if hours != 12:
hours += 12
else:
return "Invalid input!"
else:
if hours >= 0 and hours <= 23:
if hours >= 12:
meridian = "p.m."
if hours > 12:
hours -= 12
else:
meridian = "a.m."
if hours == 0:
hours = 12
return f"{hours:02d}:{minutes:02d} {meridian}"
else:
return "Invalid input!"
return f"{hours:02d}:{minutes:02d}"
user_input = input("Enter time in 12-hour or 24-hour format: ")
format_ampm_to_24H = format_ampm_to_24H(user_input)
print("Converted time:", format_ampm_to_24H)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment