Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import datetime
- from typing import List
- from typing import Tuple
- # just for type checking and bit of
- # documentation, but it's optional
- def convert_date(date: str, formats: List[str]) -> datetime.date:
- """
- Convert the date-string with the provided formats and return a date object.
- If the provided date-string does not fit to any formats or if
- the provided date-string has wrong values, the function raises a ValueError
- Method: https://docs.python.org/3.8/library/datetime.html#datetime.datetime.strptime
- Format: https://docs.python.org/3.8/library/datetime.html#strftime-strptime-behavior
- """
- for dt_format in formats:
- try:
- """
- parse the date from provided date with dt_format
- and create a date object from datetime object.
- """
- date = datetime.datetime.strptime(date, dt_format).date()
- except ValueError:
- """
- ValueError occours if the provided format was wrong or
- if the values itself are not valid.
- """
- pass
- else:
- """
- If no error happens, we know that the format fits and the values
- are in range. Return the created date object
- """
- return date
- """
- If the for loop has been finished, we know that all iterations
- throw an ValueError. So this date is wrong or
- the provided formats are wrong or the date itself was invalid.
- """
- raise ValueError(f'Invalid date: {date}')
- # the second format is isoformat (iso8601)
- # date and datetime do have the method fromisoformat()
- # and isoformat()
- date_formats: Tuple[str] = ('%d/%m/%Y', '%Y-%m-%d')
- dates = '30/02/2000, 29/02/2000, 30/02/2100, 29/02/2100, 31/02/2004, 30/02/2004, 29/02/2004, 18/03/2014, 24/08/2011, 06/10/2019, 23/09/2015, 11/01/2019, 12/09/2013, 14/03/2012, 07/03/2015, 26/12/2014, 28/07/2010, 11/07/2013, 22/11/2011, 30/10/2015, 28/12/2016, 25/10/2016, 31/12/2016, 29/01/2019, 20/03/2011, 26/11/2019, 24/08/2015'
- for date in map(str.strip, dates.split(',')):
- try:
- date_obj: datetime.date = convert_date(date, date_formats)
- except ValueError as error:
- print(error)
- else:
- print(date_obj)
- # >> Invalid date: 30/02/2000
- # >> 2000-02-29
- # >> Invalid date: 30/02/2100
- # >> Invalid date: 29/02/2100
- # >> Invalid date: 31/02/2004
- # >> Invalid date: 30/02/2004
- # >> 2004-02-29
- # >> 2014-03-18
- # >> 2011-08-24
- # >> 2019-10-06
- # >> 2015-09-23
- # >> 2019-01-11
- # >> 2013-09-12
- # >> 2012-03-14
- # >> 2015-03-07
- # >> 2014-12-26
- # >> 2010-07-28
- # >> 2013-07-11
- # >> 2011-11-22
- # >> 2015-10-30
- # >> 2016-12-28
- # >> 2016-10-25
- # >> 2016-12-31
- # >> 2019-01-29
- # >> 2011-03-20
- # >> 2019-11-26
- # >> 2015-08-24
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement