Checking for valid date input and convert appropriately

Ferrous Cranus nikos.gr33k at gmail.com
Fri Feb 22 10:07:13 EST 2013


Τη Παρασκευή, 22 Φεβρουαρίου 2013 3:35:31 μ.μ. UTC+2, ο χρήστης Lele Gaifax έγραψε:
> Ferrous Cranus <nikos.gr33k at gmail.com> writes:
> 
> 
> 
> > Let me ask it like this:
> 
> > How can i avoid using try: except: for checkign the date but instead check it with an if statement:
> 
> 
> 
> Let me answer this way: you can't, without resorting to the simple
> 
> helper functions I wrote in my previous message. 
> 
> 
> 
> Why do you dislike that solution?
> 
> 
> 
> 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.

ok, i'll just use the try: except: i was just thinking putting them all in the same if() statemt but apparently it cant be done.

Actually it can, but instead of try: i have to create a function:

def is_sane_date(date):
    parts = [int(part) for part in date.split() if part.isdigit()]
    if len(parts) == 3 and \
         1 <= parts[0] <= 31 and \
         1 <= parts[1] <= 12 and \
         1900 <= parts[2] <= 2100:
        return True
    return False

if is_sane_date(date):
    # ...

but the try: solution is much more less hassle.



More information about the Python-list mailing list