python - How to set conditions for valid dates? -
this question has answer here:
- how validate date string format in python? 5 answers
- in python, how check if date valid? 6 answers
i'm reformatting date inputs , part of using try/except function kick out invalid inputs. part of requires me set conditions is/is not valid date. example, 2017 did not have leap year, input '29-02-2017' invalid. example '31/09/2010', since september not have 31st. furthermore, '131/09/2020' invalid because of digits in day. catch drift.
a colleague mentioned created elaborate list conditions each month of year, i'm wondering if there way simplify process.
if want validate format of date (i.e. ensure single format such 01/02/99) can use
from datetime import datetime datetime_object = datetime.strptime(your_date_string_here, '%d/%m/%y')
this return datetime object if date valid, otherwise fail.
>>> datetime_object = datetime.strptime('29/02/2017', '%d/%m/%y') valueerror: day out of range month
it fail different formats, e.g.
>>> datetime_object = datetime.strptime('29-02-2017', '%d/%m/%y') traceback (most recent call last): valueerror: time data '29-02-2017' not match format '%d/%m/%y'
if want able handle multiple formats, take @ dateutil
package, can parse date formats.
from dateutil import parser dt = parser.parse(your_date_string_here)
this throw errors invalid dates, handles different formats e.g.
>>> dt = parser.parse('29-02-2017') traceback (most recent call last): valueerror: day out of range month
Comments
Post a Comment