Checking for valid date input and convert appropriately

Lele Gaifax lele at
Fri Feb 22 13:03:39 CET 2013

Ferrous Cranus <nikos.gr33k at> writes:

> I'am thinking if somehting like the follwoing work:
> if( task and ( price and price.isdigit() and price.__len__() <= 3 ) and ( date and eval( datetime.strptime(date, '%d %m %Y').strftime('%Y-%m-%d') ) ) ):

a) you should not (usually) call “dunder methods” directly, as they are
   (usually) exposed by builtin functions::

     obj.__len__() => len(obj)

b) what's the point of the eval() call above? When the strptime()
   succeds, the following strftime() call always returns a string,
   otherwise it will raise an exception and both the strftime() and the
   outer eval() won't be called.

Should I write the above, I'd go for having two helper functions, for

  def price_is_valid(price):
    return price and price.isdigit() and len(price) <= 3

  def date_is_valid(date):
      datetime.strptime(date, '%d %m %Y')
    except (TypeError, ValueError):
      return False
      return True


  if task and price_is_valid(price) and date_is_valid(date):

ciao, lele.
nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
lele at  |                 -- Fortunato Depero, 1929.

More information about the Python-list mailing list