Checking for valid date input and convert appropriately

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


Ferrous Cranus <nikos.gr33k at gmail.com> 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
example:: 

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

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

  ...

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

hth,
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 metapensiero.it  |                 -- Fortunato Depero, 1929.




More information about the Python-list mailing list