Checking for valid date input and convert appropriately

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!!
 
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)

I'am thinking if somehting like the follwoing work:

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') ) ) ):
 
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)

I'am thinking if somehting like the follwoing work:

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') ) ) ):
 
F

Ferrous Cranus

I'am thinking if somehting like the follwoing work:

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') ) ) ):

I just tried it out this workaround so to avoid having an extra try: except: but if the user doesnt enter the date properly it still raises a ValueError exception.

Is there a way to still use the if statemnt and somehow supress the message nd let else: handle it somehow?

thank you.
 
F

Ferrous Cranus

I'am thinking if somehting like the follwoing work:

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') ) ) ):

I just tried it out this workaround so to avoid having an extra try: except: but if the user doesnt enter the date properly it still raises a ValueError exception.

Is there a way to still use the if statemnt and somehow supress the message nd let else: handle it somehow?

thank you.
 
L

Lele Gaifax

Ferrous Cranus said:
I'am thinking if somehting like the follwoing work:

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') ) ) ):

a) you should not (usually) call “dunder methods†directly, as they are
(usually) exposed by builtin functions::

obj.__len__() => len(obj)

b) what's the point of the eval() call above? When the strptime()
succeds, the following strftime() call always returns a string,
otherwise it will raise an exception and both the strftime() and the
outer eval() won't be called.

Should I write the above, I'd go for having two helper functions, for
example::

def price_is_valid(price):
return price and price.isdigit() and len(price) <= 3

def date_is_valid(date):
try:
datetime.strptime(date, '%d %m %Y')
except (TypeError, ValueError):
return False
else:
return True

...

if task and price_is_valid(price) and date_is_valid(date):
...

hth,
ciao, lele.
 
F

Ferrous Cranus

Τη ΠαÏασκευή, 22 ΦεβÏουαÏίου 2013 2:03:39 μ.μ. UTC+2, ο χÏήστης Lele Gaifax έγÏαψε:
a) you should not (usually) call “dunder methods†directly, as they are

(usually) exposed by builtin functions::



obj.__len__() => len(obj)



b) what's the point of the eval() call above? When the strptime()

succeds, the following strftime() call always returns a string,

otherwise it will raise an exception and both the strftime() and the

outer eval() won't be called.



Should I write the above, I'd go for having two helper functions, for

example::



def price_is_valid(price):

return price and price.isdigit() and len(price) <= 3



def date_is_valid(date):

try:

datetime.strptime(date, '%d %m %Y')

except (TypeError, ValueError):

return False

else:

return True



...



if task and price_is_valid(price) and date_is_valid(date):

...



hth,

ciao, lele.

--

nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri

real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.

(e-mail address removed) | -- Fortunato Depero, 1929.

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:

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.

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" )

How can i write that with an if suppresing the errors if any?
 
F

Ferrous Cranus

Τη ΠαÏασκευή, 22 ΦεβÏουαÏίου 2013 2:03:39 μ.μ. UTC+2, ο χÏήστης Lele Gaifax έγÏαψε:
a) you should not (usually) call “dunder methods†directly, as they are

(usually) exposed by builtin functions::



obj.__len__() => len(obj)



b) what's the point of the eval() call above? When the strptime()

succeds, the following strftime() call always returns a string,

otherwise it will raise an exception and both the strftime() and the

outer eval() won't be called.



Should I write the above, I'd go for having two helper functions, for

example::



def price_is_valid(price):

return price and price.isdigit() and len(price) <= 3



def date_is_valid(date):

try:

datetime.strptime(date, '%d %m %Y')

except (TypeError, ValueError):

return False

else:

return True



...



if task and price_is_valid(price) and date_is_valid(date):

...



hth,

ciao, lele.

--

nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri

real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.

(e-mail address removed) | -- Fortunato Depero, 1929.

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:

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.

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" )

How can i write that with an if suppresing the errors if any?
 
F

Ferrous Cranus

i made a liitle typo at the ned, i meant this:

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" )
 
F

Ferrous Cranus

i made a liitle typo at the ned, i meant this:

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" )
 
L

Lele Gaifax

Ferrous Cranus said:
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.
 
C

Chris Angelico

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?

This is very similar to the previous threads that the OP has engaged
in recently. He asks a question of the form "How can I do X, without
using facility Y" where Y is the obvious way to do X.

http://redwing.hutman.net/~mreed/warriorshtm/ferouscranus.htm

My days of not taking him seriously are certainly coming to a middle.

ChrisA
 
A

Andreas Perstinger

Lele Gaifax said:
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?

Ferrous Cranus has proven in previous discussions (search the archives)
that he doesn't like common-sense solutions and insists on doing it his
own way (although his methods are either wrong or impossible).

Don't waste your time.

Bye, Andreas
 
F

Ferrous Cranus

Τη ΠαÏασκευή, 22 ΦεβÏουαÏίου 2013 3:35:31 μ.μ. UTC+2, ο χÏήστης Lele Gaifax έγÏαψε:
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.

(e-mail address removed) | -- 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.
 
F

Ferrous Cranus

Τη ΠαÏασκευή, 22 ΦεβÏουαÏίου 2013 3:35:31 μ.μ. UTC+2, ο χÏήστης Lele Gaifax έγÏαψε:
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.

(e-mail address removed) | -- 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.
 
T

Tim Chase

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

Then you have things like "31 2 2013" being a valid date. Also, the
hard caps at 1900 and 2100 are both pretty short-sighted. To the
best of my knowledge, there are valid dates outside that date
range :)

-tkc
 
F

Ferrous Cranus

Τη ΠαÏασκευή, 22 ΦεβÏουαÏίου 2013 5:25:41 μ.μ. UTC+2, ο χÏήστης Lele Gaifax έγÏαψε:
... not to mention it is more effective than your simplicistic check :)



ciao, lele.

--

nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri

real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.

(e-mail address removed) | -- Fortunato Depero, 1929.

:)
 
F

Ferrous Cranus

Τη ΠαÏασκευή, 22 ΦεβÏουαÏίου 2013 5:25:41 μ.μ. UTC+2, ο χÏήστης Lele Gaifax έγÏαψε:
... not to mention it is more effective than your simplicistic check :)



ciao, lele.

--

nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri

real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.

(e-mail address removed) | -- Fortunato Depero, 1929.

:)
 
F

Ferrous Cranus

Τη ΠαÏασκευή, 22 ΦεβÏουαÏίου 2013 7:38:47 μ.μ. UTC+2, ο χÏήστης Ferrous Cranus έγÏαψε:
Τη ΠαÏασκευή, 22 ΦεβÏουαÏίου 2013 5:25:41 μ.μ. UTC+2, ο χÏήστης Lele Gaifax έγÏαψε:




:)

True :)
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top