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,402
    Rep Power
    0
    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?
  2. #17
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    471
    Rep Power
    70
    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: Debian GNU/Linux 8 (desktop, home laptop, work laptop), Raspbian GNU/Linux 8 (nameserver), Ubuntu 14.04.3 LTS (HTPC), PC-BSD 10.2 (testbed), Android 4.2.1 (tablet)
  4. #18
  5. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Location
    Thessaloniki
    Posts
    1,402
    Rep Power
    0
    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!
Page 2 of 2 First 12
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo