Checking for valid date input and convert appropriately

F

Ferrous Cranus

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

=================================
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 notvalid somehow i need to catch the exception otherwise the cgi-script displays python errors.
 
M

MRAB

import datetime from datetime

Should be:

from datetime import datetime
try:
datetime.strptime( date, '%d %m %Y' )

That parses the date and discards the result.
date = date.strptime( '%Y-%m-%d' )

'date' is a string, it doesn't have a 'strptime' method.

When you parsed the date you got a datetime object; _that_ has the
'strptime' method.
 
F

Ferrous Cranus

Τη Πέμπτη, 21 ΦεβÏουαÏίου 2013 10:14:13 μ.μ. UTC+2, ο χÏήστης MRAB έγÏαψε:
Should be:



from datetime import datetime






That parses the date and discards the result.






'date' is a string, it doesn't have a 'strptime' method.



When you parsed the date you got a datetime object; _that_ has the

'strptime' method.

I don't need to store the date i just want to make sure is entered correctly.
I would like to have the user type the date like

21 02 2013
and then convert it to 2013-02-21 because thats how mysql wants the date inorder to store it.
Please show me how to write this.

Also, can you show me how to write it that if so even if the user entered date is wrong it doesn't just crash the cgi-script?i know i can use tr: expect: but i want to avoid it, somehow i need to check the date in the same ifstatemnt like i do with the other user defined varibles for validity.

if( task and ( price and price.isdigit() and price.__len__() <= 3 ) and (date and datetime.strptime(date, '%Y-%m-%d') ) ):

Thanks.
 
F

Ferrous Cranus

Τη Πέμπτη, 21 ΦεβÏουαÏίου 2013 10:14:13 μ.μ. UTC+2, ο χÏήστης MRAB έγÏαψε:
Should be:



from datetime import datetime






That parses the date and discards the result.






'date' is a string, it doesn't have a 'strptime' method.



When you parsed the date you got a datetime object; _that_ has the

'strptime' method.

I don't need to store the date i just want to make sure is entered correctly.
I would like to have the user type the date like

21 02 2013
and then convert it to 2013-02-21 because thats how mysql wants the date inorder to store it.
Please show me how to write this.

Also, can you show me how to write it that if so even if the user entered date is wrong it doesn't just crash the cgi-script?i know i can use tr: expect: but i want to avoid it, somehow i need to check the date in the same ifstatemnt like i do with the other user defined varibles for validity.

if( task and ( price and price.isdigit() and price.__len__() <= 3 ) and (date and datetime.strptime(date, '%Y-%m-%d') ) ):

Thanks.
 
M

MRAB

Τη Πέμπτη, 21 ΦεβÏουαÏίου 2013 10:14:13 μ.μ. UTC+2, ο χÏήστης MRAB έγÏαψε:

Correction: the datetime object has the 'strftime' for formatting the
date.
I don't need to store the date i just want to make sure is entered correctly.
I would like to have the user type the date like

21 02 2013
and then convert it to 2013-02-21 because thats how mysql wants the date in order to store it.
Please show me how to write this.

The 'strptime' method parses the string and returns a datetime object,
and you can then use that object's 'strftime' method to format it to
the desired string.
Also, can you show me how to write it that if so even if the user entered date is wrong it doesn't just crash the cgi-script?i know i can use tr: expect: but i want to avoid it, somehow i need to check the date in the same if statemnt like i do with the other user defined varibles for validity.
It _doesn't_ crash the cgi-script.

You're telling it to exit if an exception is raised.

If you don't want the cgi-script to exit, don't call 'exit'.
 
M

Michael Ross

Τη Πέμπτη, 21 ΦεβÏουαÏίου 2013 10:14:13 μ.μ. UTC+2, ο χÏήστης MRAB
έγÏαψε:

I don't need to store the date i just want to make sure is entered
correctly.
I would like to have the user type the date like

21 02 2013
and then convert it to 2013-02-21 because thats how mysql wants the date
in order to store it.
Please show me how to write this.

Also, can you show me how to write it that if so even if the user
entered date is wrong it doesn't just crash the cgi-script?i know i can
use tr: expect: but i want to avoid it, somehow i need to check the date
in the same if statemnt like i do with the other user defined varibles
for validity.

You *have* to try/expect in order to not have the script crash.
Think user typo: 21 02 2ß13

Personally, I'd use a javascript on the html so users can't POST invalid
dates.
I use mootools for that. It accepts 21/02/2013, 21-02-2013 and 21.02.13 as
input,
and you end up with 21.02.2013 posted to your cgi in any case.


Michael
 
F

Ferrous Cranus

Τη ΠαÏασκευή, 22 ΦεβÏουαÏίου 2013 12:03:59 Ï€.μ. UTC+2, ο χÏήστης Michael Ross έγÏαψε:
You *have* to try/expect in order to not have the script crash.

Think user typo: 21 02 2ß13



Personally, I'd use a javascript on the html so users can't POST invalid

dates.

I use mootools for that. It accepts 21/02/2013, 21-02-2013 and 21.02.13 as

input,

and you end up with 21.02.2013 posted to your cgi in any case.

i just want to check for date validity from within ha same if statemnt likei 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 ?
 
F

Ferrous Cranus

Τη ΠαÏασκευή, 22 ΦεβÏουαÏίου 2013 12:03:59 Ï€.μ. UTC+2, ο χÏήστης Michael Ross έγÏαψε:
You *have* to try/expect in order to not have the script crash.

Think user typo: 21 02 2ß13



Personally, I'd use a javascript on the html so users can't POST invalid

dates.

I use mootools for that. It accepts 21/02/2013, 21-02-2013 and 21.02.13 as

input,

and you end up with 21.02.2013 posted to your cgi in any case.

i just want to check for date validity from within ha same if statemnt likei 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 ?
 
F

Ferrous Cranus

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?
 
F

Ferrous Cranus

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?
 
M

Mark Lawrence

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?

I suggest testing your code at the interactive prompt, so something like.

c:\Users\Mark>python
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32
bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor 'strftime' requires a 'datetime.date' object but
received a 'str'
 
M

Michael Ross

Τη ΠαÏασκευή, 22 ΦεβÏουαÏίου 2013 12:03:59 Ï€.μ. UTC+2, ο χÏήστης Michael
Ross έγÏαψε:

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 ?


I pretend not to know, try it out?

And try with invalid inputs, too:
211 02 2013
21 99 2013
31 02 2013
 
F

Ferrous Cranus

Please i have been trying hours for this:

try:
datetime.strptime(date, '%d m% %Y')
date = date.strftime('%Y-%m-%d')
except:
print( "<h2>date not propetly entered." )
sys.exit(0)
===========================

the user enters 21 02 2013

a) i just need to check if its in accepted format
b) then truncate the given date to mysql format

That's all i want to do and i cant make it work. Plese tell me how to write this.

I have tried anything i can think of.
 
F

Ferrous Cranus

Please i have been trying hours for this:

try:
datetime.strptime(date, '%d m% %Y')
date = date.strftime('%Y-%m-%d')
except:
print( "<h2>date not propetly entered." )
sys.exit(0)
===========================

the user enters 21 02 2013

a) i just need to check if its in accepted format
b) then truncate the given date to mysql format

That's all i want to do and i cant make it work. Plese tell me how to write this.

I have tried anything i can think of.
 
M

Michael Ross

Please i have been trying hours for this:

Don't do that: Spending hours on being stuck. Take a break. Call it a
night.
Brain needs time to unstick itself.


Besides:
from datetime import date
entry='31 03 2013'
day, month, year = int(entry[:2]), int(entry[3:5]), int(entry[6:])
mydate=date(year,month,day)
mydate.strftime('%Y-%m-%d')
'2013-03-31'




try:
datetime.strptime(date, '%d m% %Y')
date = date.strftime('%Y-%m-%d')
except:
print( "<h2>date not propetly entered." )
sys.exit(0)
===========================

the user enters 21 02 2013

a) i just need to check if its in accepted format
b) then truncate the given date to mysql format

That's all i want to do and i cant make it work. Plese tell me how to
write this.

I have tried anything i can think of.
 
F

Ferrous Cranus

Τη ΠαÏασκευή, 22 ΦεβÏουαÏίου 2013 2:57:03 Ï€.μ. UTC+2, ο χÏήστης Michael Ross έγÏαψε:
Don't do that: Spending hours on being stuck. Take a break. Call it a

night.

Brain needs time to unstick itself.
Besides:
from datetime import date
entry='31 03 2013'
day, month, year = int(entry[:2]), int(entry[3:5]), int(entry[6:])

mydate=date(year,month,day)
mydate.strftime('%Y-%m-%d')

'2013-03-31'

Tis seems very nice solution but also we need to check the user input for validity. What if the user entered: 29 15 2013 ?

i tried to use your method applying some date validation check but that also failed for me:

try:
if( datetime.strptime(date, '%d m% %Y') ):
day, month, year = int(date[:2]), int(date[3:5]), int(date[6:])
date = date(year, month, day)
date = date.strftime('%Y-%m-%d')
except:
print "....."
========================

Isn't method strptime check the user input for validity?
 
F

Ferrous Cranus

Τη ΠαÏασκευή, 22 ΦεβÏουαÏίου 2013 2:57:03 Ï€.μ. UTC+2, ο χÏήστης Michael Ross έγÏαψε:
Don't do that: Spending hours on being stuck. Take a break. Call it a

night.

Brain needs time to unstick itself.
Besides:
from datetime import date
entry='31 03 2013'
day, month, year = int(entry[:2]), int(entry[3:5]), int(entry[6:])

mydate=date(year,month,day)
mydate.strftime('%Y-%m-%d')

'2013-03-31'

Tis seems very nice solution but also we need to check the user input for validity. What if the user entered: 29 15 2013 ?

i tried to use your method applying some date validation check but that also failed for me:

try:
if( datetime.strptime(date, '%d m% %Y') ):
day, month, year = int(date[:2]), int(date[3:5]), int(date[6:])
date = date(year, month, day)
date = date.strftime('%Y-%m-%d')
except:
print "....."
========================

Isn't method strptime check the user input for validity?
 
R

rob.marshall17

The datetime function: strptime() DOES check the date for validity. So try something like:

from datetime import datetime

def get_date():
while True:
try:
date_in = raw_input("Enter date (dd mm yyyy): ")
date_out = datetime.strptime(date_in,"%d %m %Y").strftime("%Y-%m-%d")
return date_out
except ValueError:
print "Invalid date: {}, try again...".format(date_in)
 
R

rob.marshall17

The datetime function: strptime() DOES check the date for validity. So try something like:

from datetime import datetime

def get_date():
while True:
try:
date_in = raw_input("Enter date (dd mm yyyy): ")
date_out = datetime.strptime(date_in,"%d %m %Y").strftime("%Y-%m-%d")
return date_out
except ValueError:
print "Invalid date: {}, try again...".format(date_in)
 
F

Ferrous Cranus

Τη ΠαÏασκευή, 22 ΦεβÏουαÏίου 2013 8:20:20 Ï€.μ. UTC+2, ο χÏήστης (e-mail address removed) έγÏαψε:
The datetime function: strptime() DOES check the date for validity. So try something like:



from datetime import datetime



def get_date():

while True:

try:

date_in = raw_input("Enter date (dd mm yyyy): ")

date_out = datetime.strptime(date_in,"%d %m %Y").strftime("%Y-%m-%d")

return date_out

except ValueError:

print "Invalid date: {}, try again...".format(date_in)

Thank you very very much!! i cannot beleive that it was so easy, a matter of one line of coding!

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

Cna you please explain in to me?
This line checks the date variable for valid pattern entry and then also tranforms the date to the othjer pattern?

And if there is a way to embed this line to the existing if() statemtn along with the othwr variables check that would be perfect!!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top