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

    Join Date
    Jun 2003
    Location
    Thessaloniki
    Posts
    1,285
    Rep Power
    13

    Checking for valid date input and convert appropriately


    Code:
    import datetime from datetime
    
    try:
        datetime.strptime( date, '%d %m %Y' )
        date = date.strptime( '%Y-%m-%d' )
    except ValueError:
        print( "<h2><font color=red>H ημερομηνία πρέπει να εισαχθεί στην σωστή μορφή => 21 05 2013!" )
        sys.exit(0)
    Hello, a have an html that among other thing require the user to insert a valid date.
    The user must enter a date like "21 02 2013"

    a) first i need to check if the entered date was inserted properly as above
    b) convert the entered date to '%Y-%m-%d' which is an appropriate mysql date type format.

    Also it would be nice if i could check the user entered date within an if statement like i check all my other fields instead of creating an extra ;try' statemnt just for checking tha date

    Code:
    if( task and (price and price.isdigit() and price.__len__() <= 3) and **check_for_valid_date**):
    Thank you for your help.
    What is now proved was once only imagined!
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Location
    Iran
    Posts
    149
    Rep Power
    140
    Hello there,


    I think using a regular expression could be useful for this problem (for more information on module RE click here)

    Using Python 3, I would write the following (inspired by your code sample in the if statement)

    Code:
    from datetime import datetime
    import re
    
    def check_for_valid_date(param_dateStr):
        progDatePattern = re.compile("^((?P<day>\d{2}) (?P<month>\d{2}) (?P<year>\d{4}))$")
        matchDate = progDatePattern.match(param_dateStr)
        if matchDate:
            try:
                dateValue = datetime(
                                        year=int(matchDate.group("year")),
                                        month=int(matchDate.group("month")),
                                        day=int(matchDate.group("day"))
                                    )
            except ValueError:
                return False
                
            return True
            
        else:
            return False
    
    
            
    # So you other tests of your if statement here
    if check_for_valid_date(input("Enter a date: ")):
        print("The date is valid")
    else:
        print("The date is not valid")

    Regards,
    Dariyoosh
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,966
    Rep Power
    481
    Would separating the code you've already got into its own function help?
    [code]Code tags[/code] are essential for python code and Makefiles!
  6. #4
  7. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Location
    Thessaloniki
    Posts
    1,285
    Rep Power
    13
    Guys i want to keep things as simple as possible, i do not want to use an extra function for what i need. Just

    a) first i need to check if the entered date was inserted properly as above
    b) convert the entered date to '%Y-%m-%d' which is an appropriate mysql date type format.

    Do i have somehtign wrong in my initial post?
    What is now proved was once only imagined!
  8. #5
  9. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Location
    Thessaloniki
    Posts
    1,285
    Rep Power
    13
    let me ask it like this:

    Code:
    if( task and ( price and price.isdigit() and price.__len__() <= 3 ) and ( date and datetime.strptime(date, '%Y-%m-%d') ) ):
    I want it to be written like the above, but if the user entered date is not valid somehow i need to catch the exception otherwise the cgi-script displays python errors.
    What is now proved was once only imagined!
  10. #6
  11. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,966
    Rep Power
    481
    The first line of your first post doesn't work in my python implementations, but I expect that's from a careless post rather than code you tried to execute.
    Anyway, strptime apparently uses ValueError to announce garbage input. Regular expressions might be terrible because you'd have to encode knowledge about dates into the RE, except that if you limit the range of years you wouldn't have to worry about "every 400 year" rules. (I doubt that's an issue, except that we just had one!)
    Code:
    >>> from datetime import datetime
    >>> datetime.strptime( '03 04 1921', '%d %m %Y' ).strftime('%Y-%m-%d')
    '1921-04-03'
    >>> datetime.strptime( '31 2 1921', '%d %m %Y' ).strftime('%Y-%m-%d')
    datetime.strptime( '31 2 1921', '%d %m %Y' ).strftime('%Y-%m-%d')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib/python3.2/_strptime.py", line 500, in _strptime_datetime
        tt, fraction = _strptime(data_string, format)
      File "/usr/lib/python3.2/_strptime.py", line 465, in _strptime
        datetime_date(year, 1, 1).toordinal() + 1
    ValueError: day is out of range for month
    >>>
    If you're only willing to import functions then you'll need to look for a module that validates dates without throwing an exception. Or you could surround a huge block of code with try: except: in which you'd test the various possible tracebacks. I wouldn't do that, and I doubt you will either.
    [code]Code tags[/code] are essential for python code and Makefiles!
  12. #7
  13. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Location
    Thessaloniki
    Posts
    1,285
    Rep Power
    13
    iam willign to use regular expressions and i will be just carefull when i enter dates fors example i wont enter a monnt > 12

    can you say me how to gain user input like

    21 02 2013
    and then
    store it as
    2013-02-21

    please?
    What is now proved was once only imagined!
  14. #8
  15. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,966
    Rep Power
    481
    Use groups and then write the substitution as
    r'\3-\2-\1'

    Code:
    >>> re.sub('([0-3]?[0-9]) ([01]?[0-9]) ([12][09][019][0-9])',r'\3-\2-\1','2 3 1999')
    But since there isn't any action based on validation, these expressions are absurdly complicated.
    Code:
    >>> re.sub(r'(\w+) (\w+) (\w+)', r'\3-\2-\1','2 3 1999')
    '1999-3-2'
    Last edited by b49P23TIvg; February 21st, 2013 at 05:21 PM.
    [code]Code tags[/code] are essential for python code and Makefiles!
  16. #9
  17. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Location
    Thessaloniki
    Posts
    1,285
    Rep Power
    13
    I'am a little confused:
    How does the following line need to be written as to check

    Code:
    if( task and ( price and price.isdigit() and price.__len__() <= 3 ) and ( date and datetime.strptime(date, '%d-%m-%Y') ) ):
    and then i have to do what to save the date to a proper MySQL needed type?

    please show me in detail so i can understand, thanks.
    What is now proved was once only imagined!
  18. #10
  19. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Location
    Thessaloniki
    Posts
    1,285
    Rep Power
    13
    i just want to check for date validity from within ha same if statemnt like i check the other variables and i tried a regualr expression just now:

    if( task and ( price and price.isdigit() and price.__len__() <= 3 ) and ( date and re.search( r'(\d+) (\d+) (\d+)', date ) ) ):

    Do i ahve somehting wrong in it?

    will the if become true if the user enters 21 02 2013 ?

    Then i try to save the date as MySQL wants but it just aint happening:

    date = datetime.strftime(date, '%Y-%m-%d')

    Can you help me please save the user entered date to MySQL format?
    What is now proved was once only imagined!
  20. #11
  21. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,966
    Rep Power
    481
    Code:
    >>> date='88 88 888888'
    >>> ( date and re.search( r'(\d+) (\d+) (\d+)', date ) )  # true
    <_sre.SRE_Match object at 0x7f4ca41cd9b0>
    >>> re.sub(r'(\d+) (\d+) (\d+)', r'\3-\2-\1', date)
    '888888-88-88'
    >>>
    You've lost date validation. I guess that's why they give those pop-up calendars. Valid dates can be wrong dates. That's no longer your problem. Or it's a different problem.
    [code]Code tags[/code] are essential for python code and Makefiles!
  22. #12
  23. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Location
    Thessaloniki
    Posts
    1,285
    Rep Power
    13
    ok ill switch to datetime then:

    Code:
    try:
    		if( datetime.strptime(date, '%d m% %Y') ):
    			date = date.strftime('%Y-%m-%d')
    	except:
    		print( "<h2><font color=red>Η ημερομηνία πρέπει να εισαχθεί στην μορφή π.χ. '21 02 2013'" )
    		print '''<meta http-equiv="REFRESH" content="5;url=http://superhost.gr/cgi-bin/pelatologio.py?log=%s">''' % name
    		sys.exit(0)

    but this fails too.

    can you make it work?
    What is now proved was once only imagined!
  24. #13
  25. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Location
    Thessaloniki
    Posts
    1,285
    Rep Power
    13
    The solution was so simple! i cannot believe we couldnt see it so many hours!

    Code:
    date = datetime.strptime(date,"%d %m %Y").strftime("%Y-%m-%d")
    What is now proved was once only imagined!
  26. #14
  27. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Location
    Thessaloniki
    Posts
    1,285
    Rep Power
    13
    I'am trying to embed the date check into the if i have:

    Code:
    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') ) ) ):
    but that doesnt seem to work...
    What is now proved was once only imagined!
  28. #15
  29. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    439
    Rep Power
    67
    Originally Posted by Nik
    The solution was so simple! i cannot believe we couldnt see it so many hours!

    Code:
    date = datetime.strptime(date,"%d %m %Y").strftime("%Y-%m-%d")
    Actually that solution was told to you a while ago (see above).

    Code:
    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') ) ) ):
    Of course it doesn’t. Why did you insert eval() there?
    My armada: openSUSE 13.2 (home desktop, work desktop), openSUSE 13.1 (home laptop), Debian GNU/Linux 7.7.0 (mini laptop), Ubuntu 14.04 LTS (server), Android 4.2.1 (tablet), Windows 7 Ultimate (testbed)
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo