Last active
December 29, 2015 17:29
-
-
Save robjwells/7704957 to your computer and use it in GitHub Desktop.
Convert 24-hour time to formatted 12-hour time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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