diff --git a/scenes/dates.py b/scenes/dates.py new file mode 100644 index 0000000000000000000000000000000000000000..21e1bfa271ad5578aaf69004d6f1a70c85cf066b --- /dev/null +++ b/scenes/dates.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +""" +This module aims to deal with dates +""" +import datetime + + +def str2datetime(datestr): + """ + Converts an input date as string into a datetime instance. + + Args: + datestr: date (str) in the format "YYYY-MM-DD" or "DD/MM/YYYY" or "DD-MM-YYYY" + + Returns: + A datetime.datetime instance + + """ + # source (with a few enhancements): + # https://stackoverflow.com/questions/23581128/how-to-format-date-string-via-multiple-formats-in-python + assert isinstance(str, datestr), "Input must be a str!" + formats = ('%Y-%m-%d', '%d/%m/%Y', '%d-%m-%Y') + for fmt in formats: + try: + return datetime.datetime.strptime(datestr, fmt) + except ValueError: + pass + raise ValueError(f'No valid date format found. Accepted formats are {formats}. Input was: {datestr}') + + +def any2datetime(str_or_datetime): + """ + Normalizes the input such as the returned object is a datetime.datetime instance. + + Args: + str_or_datetime: a str (see `str2datetime()` for supported dates formats) or a datetime.datetime + + Returns: + A datetime.datetime instance + + """ + if isinstance(datetime.datetime, str_or_datetime): + return str_or_datetime + assert isinstance(str, str_or_datetime), "Date must be a str, or a datetime.datetime instance!" + return dates.str2datetime(str_or_datetime) \ No newline at end of file