Converting date from HTML form to datetime

The following code works fine in converting two search criteria to datetimes:

            for _key in request.GET:
                if _key == "txtCriteriaDateFrom":
                    _dateFromStr = request.GET[_key]
                    _dateFrom = datetime.strptime(_dateFromStr, '%Y-%m-%d') 
                if _key == "txtCriteriaDateTo":
                    _dateToStr = request.GET[_key]
                    _dateTo = datetime.strptime(_dateToStr, '%Y-%m-%d')

The data is coming into the GET object from a <input type=‘date’ control and that wants the Y-m-d format.

I’m just a little concerned that the format is very specific and that makes the above code very brittle and liable to break in the future.

Is there a more generic way of converting a string with a valid datetime format, but which could be any format (the US standard m-d-Y being a good example)?

Or is there a better way of doing this completely?

I would say that there really isn’t. You want an unambiguous notation to be used in your forms to prevent misunderstanding such as the difference between “m-d-y” and “d-m-y” - made worse if you allow now for 2-digit years.

Having said that, you do have the DATE_INPUT_FORMATS setting available to you to allow for different formats to be acceptable as input. But that’s only directly useful if you’re assigning those values to a field. (You could look at the implementation to see if there are classes / methods that you could take advantage of.)

No, that’s fine, I just wanted to check. I can work the UI error handling around this.

I’m finding my bioinformatic colleagues are entirely optimistic about potential issues like this, whereas I’m entirely cynical…or realistic, depending on viewpoint.

The degree of “brittleness” in this case is going to depend upon the front-end building the URL with those query parameters. If it’s user-entered data in a form, they need to be taught what the proper format is.
If it’s being generated from some type of input widget, then yes - there’s a chance that that widget changing might break your code - but that’s a change you would need to know about anyway. In the ideal world, the JS widget being used accepts some type of configuration parameter specifying the supplied data format.