Skip to content

Instantly share code, notes, and snippets.

@cdw9
Created December 17, 2019 20:31
Show Gist options
  • Save cdw9/fbfb89eba62c42ebd43ae4c63ccc8852 to your computer and use it in GitHub Desktop.
Save cdw9/fbfb89eba62c42ebd43ae4c63ccc8852 to your computer and use it in GitHub Desktop.
Taking separate date and time strings (which are not following a specific format), turn them into datetime objects and return [start, end]
def event_dates(date, time):
"""Takes the event's date and time fields,
returns a start date and end date (if applicable)
example date: "2017/09/16 00:00:00 GMT-4"
example time: "11:00 am" or "9:00am - 11:00pm"
"""
if not date:
return [None, None]
date = date.replace('GMT-4', 'America/New_York')
if not time:
return [date, date]
time_no_dots = time.replace('.', '').replace('–', '-')
evtime = time_no_dots.lower().split('-')
start_end = []
for item in evtime:
am_or_pm = 'am' # default to am if not specified
if 'am' in item:
item = item.replace('am', '')
elif 'pm' in item or 'pm' in time_no_dots:
am_or_pm = 'pm'
item = item.replace('pm', '')
if 'noon' in item.lower():
am_or_pm = 'pm'
item = '12:00'
units = item.strip().split(':')
if am_or_pm == 'pm':
try:
if units[0] != '12':
units[0] = str(int(units[0].split(' ')[0]) + 12)
except ValueError:
start_end.append(date)
continue
if len(units) == 1:
new_time = ':'.join(units) + ':00'
else:
new_time = ':'.join(units)
try:
datetime.strptime(new_time, '%H:%M')
start_end.append(date.replace('00:00:00', new_time))
except ValueError:
start_end.append(date)
if len(start_end) == 1:
start_end.append(None)
return start_end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment