Skip to content

Instantly share code, notes, and snippets.

@MattWoodhead
Created August 26, 2017 11:09
Show Gist options
  • Save MattWoodhead/47291ec7810289d51d55f53b819bb0ed to your computer and use it in GitHub Desktop.
Save MattWoodhead/47291ec7810289d51d55f53b819bb0ed to your computer and use it in GitHub Desktop.
A date converter function that can handle multiple date inputs types in the iso format and return a datetime.date object
import string
import datetime as dt
def date_converter(date):
""" converts multiple date formats into a datetime object """
if isinstance(date, str):
try:
d = ""
for char in date:
if char in string.punctuation:
char = "-"
d += char
date = "-".join([str(int(i)) for i in d.split("-")])
print(d)
date_format = "%Y-%m-%d"
return dt.datetime.strptime(date, date_format).date()
except:
raise TypeError("The string provided is not a valid date"
" - Use the YYYY-MM-DD format")
elif isinstance(date, tuple):
try:
return dt.datetime(date).date()
except:
raise TypeError("The tuple provided is not a valid date"
" - Use the (YYYY, MM, DD) format")
elif isinstance(date, dt.datetime):
return date.date()
elif isinstance(date, dt.date):
return date
else:
raise TypeError("The date_converter function is not compatible"
" with this date type")
if __name__ == "__main__":
today = dt.datetime.today()
print(date_converter(today))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment