Page 2 of 2 First 12
  • Jump to page:
    #16
  1. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Location
    Thessaloniki
    Posts
    1,280
    Rep Power
    13
    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:

    Code:
    if ( datetime.strptime(date, '%d %m %Y') ): 
         date = datetime.strptime(date, '%d %m %Y').strftime('%Y-%m-%d') 
    else: 
         print( "Date wasn't entered properly" )
    I'am trying this but if user entered date is noit on the acceptible format it raises an exception.
    If i surround it with eval() its still raises an excpetion.

    Code:
    if ( eval( datetime.strptime(date, '%d %m %Y')  ) ): 
         date = datetime.strptime(date, '%d %m %Y').strftime('%Y-%m-%d') 
    else: 
         print( "Date wasn't entered properly" )
    How can i write that with an if suppresing the errors if any?
    What is now proved was once only imagined!
  2. #17
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    430
    Rep Power
    66
    Originally Posted by Nik
    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:
    Well itís possible but demands lots of extra work. First you create a function to do sanity checks:

    Code:
    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
    And then you use this in your if test:

    Code:
    if is_sane_date(date):
        # ...
    But exceptions are there for a purpose!
    My armada: openSUSE 13.1 (home desktop, home laptop), Crunchbang Linux 11 (mini laptop, work laptop), Android 4.2.1 (tablet)
  4. #18
  5. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Location
    Thessaloniki
    Posts
    1,280
    Rep Power
    13
    ok, i'll just use the try: except: i was just thinking putting them all in the same if() statemt but apparently it can't be done without creatign extra functions!

    thank you!
    What is now proved was once only imagined!
Page 2 of 2 First 12
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo