Skip to content

Instantly share code, notes, and snippets.

@Plaudenslager
Last active July 17, 2016 16:06
Show Gist options
  • Save Plaudenslager/5c2d8ede9bf05cac50dba8a0f9cc79db to your computer and use it in GitHub Desktop.
Save Plaudenslager/5c2d8ede9bf05cac50dba8a0f9cc79db to your computer and use it in GitHub Desktop.
convert characters (like '10:05 am') into python datetime format, despite likely formatting errors; list of errors / formats is extensible
# Import times with a variety of broken formatting
# g_time_string is a character string
# g_time is the datetime object to produce
if g_time_string[-1] == 'n':
g_time_string = g_time_string[0:-1] + "m"
g_time = None
# Various formatting for time, including common mistakes
time_formats = ["%I:%M %p", "%I:%M%p", "%I::%M %p", "%I;%M %p", "%I: %M %p", "%I:%M", "%I;%M%p",
"%I:%M p%p", "%I:%M0%p"]
for tf in time_formats:
# The try / except captures the error so we can attempt the next format
try:
g_time = datetime.datetime.strptime(g_time_string, tf)
break
except ValueError:
continue
# If we couldn't match any formatting, re-raise the error
if g_time is None:
raise ValueError('Could not match time format for %s' %g_time_string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment