Skip to content

Instantly share code, notes, and snippets.

@robjwells
Last active December 29, 2015 17:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robjwells/7704957 to your computer and use it in GitHub Desktop.
Save robjwells/7704957 to your computer and use it in GitHub Desktop.
Convert 24-hour time to formatted 12-hour time
#!/usr/local/bin/python3
import sys
import re
input_text = sys.stdin.read()
regex_24 = re.compile(r'''\b
([01][0-9]|2[0-3]) # Hour (00-23)
([0-5][0-9]) # Mins (00-59)
\b''', flags=re.VERBOSE)
def convert_24(match):
hour, minute = match.groups()
hour = int(hour)
if hour < 12:
suffix = 'am'
else:
suffix = 'pm'
if hour == 0:
hour = '12'
elif hour > 12:
hour -= 12
if minute == '00':
return '{h}{sf}'.format(h=hour, sf=suffix)
else:
return '{h}.{m}{sf}'.format(h=hour, m=minute, sf=suffix)
working = regex_24.sub(convert_24, input_text)
print(working)
#!/usr/local/bin/python3
import sys
import re
from datetime import time
input_text = sys.stdin.read()
regex_24 = re.compile(r'''\b
([01][0-9]|2[0-3]) # Hour (00-23)
:?
([0-5][0-9]) # Mins (00-59)
\b''', flags=re.VERBOSE)
def convert_24(match):
hour, minute = [int(part) for part in match.groups()]
tm = time(hour, minute)
fmt = '%-I.%M%p' if minute else '%-I%p'
return tm.strftime(fmt).lower()
working = regex_24.sub(convert_24, input_text)
print(working)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment