2

I'm reformatting date inputs and part of that is using the try/except function to kick out invalid inputs. Part of this requires me to set conditions for what is/is not a valid date. For example, 2017 did not have a leap year, so input '29-02-2017' would be invalid. Another example is '31/09/2010', since September does not have a 31st. Furthermore, '131/09/2020' is also invalid because of the digits in the day. You catch my drift.

A colleague mentioned they created an elaborate list with conditions for each month of the year, but I'm wondering if there is a way to simplify this process.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • In case it's helpful, here's a sample of some production code I wrote that parses a month/day from data retrieved from a text box. This application never cares about year, so I set it to the dummy value of `2000` just so it'll parse. https://gist.github.com/anonymous/98efe5bb46c4a790c3b8d51e2a594132 – Adam Smith Sep 13 '17 at 22:05
  • @AdamSmith I appreciate it! –  Sep 13 '17 at 22:11
  • @hamsterbyte No problem. N.B. that the function is designed to let a failing date bubble up to the next layer of code. i.e. the calling code should handle a failed date (since `make_date` controls neither the source of the date string nor does it have responsibility to talk to the UI) – Adam Smith Sep 13 '17 at 22:13

1 Answers1

0

If you also want to validate the format of the date (i.e. ensure it is all a single format such as 01/02/99) then you can use

from datetime import datetime
datetime_object = datetime.strptime(your_date_string_here, '%d/%m/%Y')

This will return a datetime object if the date is valid, otherwise it will fail.

>>> datetime_object = datetime.strptime('29/02/2017', '%d/%m/%Y')
ValueError: day is out of range for month

It will also fail for 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' does not match format '%d/%m/%Y'

If you want to be able to handle multiple formats, take a look at the dateutil package, which can parse most date formats.

from dateutil import parser
dt = parser.parse(your_date_string_here)

This will throw errors for invalid dates, but handles different formats e.g.

>>> dt = parser.parse('29-02-2017')
Traceback (most recent call last):
ValueError: day is out of range for month
mfitzp
  • 15,275
  • 7
  • 50
  • 70