Skip to content

Instantly share code, notes, and snippets.

@rochacbruno
Forked from dnouri/gist:867230
Created March 12, 2011 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rochacbruno/867299 to your computer and use it in GitHub Desktop.
Save rochacbruno/867299 to your computer and use it in GitHub Desktop.
def guess_time(s):
"""
>>> guess_time('20:00')
(20, 0)
>>> guess_time('23:59')
(23, 59)
>>> guess_time('20:00foo')
(20, 0)
>>> guess_time('9pm')
(21, 0)
>>> guess_time('10am')
(10, 0)
>>> guess_time('10:30am')
(10, 30)
>>> guess_time('10:30 pm')
(22, 30)
>>> guess_time('10AMbar')
(10, 0)
>>> guess_time('fubar')
"""
# See http://docs.python.org/library/time.html#time.strftime
letters_to_fmts = [
(8, ['%I:%M %p']),
(7, ['%I:%M%p']),
(5, ['%I %p', '%H:%M']),
(4, ['%I%p']),
]
for letters, fmts in letters_to_fmts:
s1 = s[:letters]
for fmt in fmts:
try:
struct = time.strptime(s1, fmt)
except ValueError:
continue
else:
return (struct.tm_hour, struct.tm_min)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment