943,589 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Marked Solved
  • Views: 1628
  • Python RSS
Sep 25th, 2009
0

Using Datetime for user input

Expand Post »
Hi

I want to prompt the user to enter the date dd/mm/year and use this later as part of filename and later as object in file(if this helps searching). Does using datetime ensure that user input will be a valid input? I would like the output to be year-mm-dd

My below version errors.

#This doesn't error but also doesn't prompt me for input.

Python Syntax (Toggle Plain Text)
  1. from datetime import date
  2. def ObtainDate():
  3. input = raw_input("Type Date dd/mm/year: ")
  4. d = datetime.strptime(input, "%y-%m-%d")
  5. print ObtainDate
Last edited by flebber; Sep 25th, 2009 at 9:02 pm.
Similar Threads
Reputation Points: 10
Solved Threads: 3
Light Poster
flebber is offline Offline
37 posts
since Aug 2009
Sep 25th, 2009
0

Re: Using Datetime for user input

Firstly 'input' is a reserved word in python, it's used to get input from the user, (rather like raw_input!). So that's why this line of code fails to do anything:
PYTHON Syntax (Toggle Plain Text)
  1. input = raw_input("Type Date dd/mm/year: ")
Change your variable 'input' to something like 'userInput' or just anything that isn't a reserved word and you will get your prompt!

Secondly...No I don't think that strptime will work used like that! if your users enter anything other than yy-mm-dd, it will bomb out with an error!
But if you use a try: except: block inside a loop, you should be able to get the user to repeatedly enter the date until the format is correct!

Check this out:
PYTHON Syntax (Toggle Plain Text)
  1. import datetime
  2. def ObtainDate():
  3. isValid=False
  4. while not isValid:
  5. userIn = raw_input("Type Date dd/mm/yy: ")
  6. try: # strptime throws an exception if the input doesn't match the pattern
  7. d = datetime.datetime.strptime(userIn, "%d/%m/%y")
  8. isValid=True
  9. except:
  10. print "Doh, try again!\n"
  11. return d
  12.  
  13. #test the function
  14. print ObtainDate()

I've not done any exception handling code for a while, but there should be a way of outputting to the user the reason that the exception occurred.

I'll leave that up to you to look up!

Cheers for now,
Jas
Reputation Points: 590
Solved Threads: 123
Practically a Master Poster
JasonHippy is offline Offline
672 posts
since Jan 2009
Sep 26th, 2009
0

Re: Using Datetime for user input

Click to Expand / Collapse  Quote originally posted by JasonHippy ...
Firstly 'input' is a reserved word in python, it's used to get input from the user, (rather like raw_input!). So that's why this line of code fails to do anything:
PYTHON Syntax (Toggle Plain Text)
  1. input = raw_input("Type Date dd/mm/year: ")
Change your variable 'input' to something like 'userInput' or just anything that isn't a reserved word and you will get your prompt!

Secondly...No I don't think that strptime will work used like that! if your users enter anything other than yy-mm-dd, it will bomb out with an error!
But if you use a try: except: block inside a loop, you should be able to get the user to repeatedly enter the date until the format is correct!

Check this out:
PYTHON Syntax (Toggle Plain Text)
  1. import datetime
  2. def ObtainDate():
  3. isValid=False
  4. while not isValid:
  5. userIn = raw_input("Type Date dd/mm/yy: ")
  6. try: # strptime throws an exception if the input doesn't match the pattern
  7. d = datetime.datetime.strptime(userIn, "%d/%m/%y")
  8. isValid=True
  9. except:
  10. print "Doh, try again!\n"
  11. return d
  12.  
  13. #test the function
  14. print ObtainDate()

I've not done any exception handling code for a while, but there should be a way of outputting to the user the reason that the exception occurred.

I'll leave that up to you to look up!

Cheers for now,
Jas
Awesome I like it just one question why does the line below have datetime twice?

d = datetime.datetime.strptime(userIn, "%d/%m/%y")

I think with exception handling that getting the user a reason as to why input was wrong could use the try: obj.method but I will need to look into this further.
Reputation Points: 10
Solved Threads: 3
Light Poster
flebber is offline Offline
37 posts
since Aug 2009
Sep 26th, 2009
0

Re: Using Datetime for user input

Click to Expand / Collapse  Quote originally posted by flebber ...
Awesome I like it just one question why does the line below have datetime twice?

d = datetime.datetime.strptime(userIn, "%d/%m/%y")
It's the only way I could access the strptime function.
The first datetime refers to the datetime package, the second refers to the datetime class.

In my import I could have used something like:
PYTHON Syntax (Toggle Plain Text)
  1. import datetime as dt
This gives the datetime package an alias (dt). So to call the strptime function I'd need to use:
PYTHON Syntax (Toggle Plain Text)
  1. dt.datetime.strptime(userInput, pattern)

So my strptime function call breaks into the following parts:
packageName.className.function(parameter1, parameter2)
or:
datetime.datetime.strptime(userInput, "%d/%m/%y")

Hope that clarifies things for you!

Cheers for now,
Jas.
Last edited by JasonHippy; Sep 26th, 2009 at 8:22 am.
Reputation Points: 590
Solved Threads: 123
Practically a Master Poster
JasonHippy is offline Offline
672 posts
since Jan 2009
Sep 26th, 2009
0

Re: Using Datetime for user input

To find the error class simply create the error ...
python Syntax (Toggle Plain Text)
  1. import datetime as dt
  2.  
  3. # the date has to be entered in dd/mm/yy format
  4. # entering dd/mm/yyyy by mistake will create an error
  5. # the error class will be --> ValueError
  6. test_date = "15/07/2003"
  7.  
  8. d1 = dt.datetime.strptime(test_date, "%d/%m/%y")
Also be aware that d1 will be a datetime object and not a string, so you have to do some simple extra coding ...
python Syntax (Toggle Plain Text)
  1. import datetime as dt
  2.  
  3. # date has been entered in dd/mm/yy format
  4. test_date = "15/07/03"
  5.  
  6. d1 = dt.datetime.strptime(test_date, "%d/%m/%y")
  7.  
  8. print d1, type(d1) # 2003-07-15 00:00:00 <type 'datetime.datetime'>
  9.  
  10. # convert datetime object to a 10 character string
  11. d2 = str(d1)[:10]
  12.  
  13. print d2, type(d2) # 2003-07-15 <type 'str'>
  14.  
  15. # now you can use string d2 to create filenames
  16. fname = "data.dat"
  17. new_fname = d2 + fname
  18.  
  19. print new_fname # 2003-07-15data.dat
This file name should sort well.
Last edited by vegaseat; Sep 26th, 2009 at 10:04 am.
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Sep 26th, 2009
0

Re: Using Datetime for user input

I really like it a lot, and it works well thanks jasonHippy and Vegaseat. The only thing I am going to look into when I am not so tired is that if you supply a correctly formatted date but say you use the 31st September as 31/09/09 which doesn't exist it errors "Try again! dd/mm/yy" intimating its a format error when its a date doesn't exist error.

Which simply means I need to catch 2 errors.

Python Syntax (Toggle Plain Text)
  1. mport datetime as dt
  2. def ObtainDate():
  3. isValid=False
  4. while not isValid:
  5. userIn = raw_input("Type Date dd/mm/yy: ")
  6. try: # strptime throws an exception if the input doesn't match the pattern
  7. d1 = dt.datetime.strptime(userIn, "%d/%m/%y")
  8. isValid=True
  9. #Perhaps set another try here.
  10. print d1, type(d1) # 2003-07-15 00:00:00 <type 'datetime.datetime'>
  11. "convert datetime object to a 10 character string"
  12. d2 = str(d1)[:10]
  13. print d2, type(d2) # 2003-07-15 <type 'str'>
  14. except:
  15. print "Try again! dd/mm/yy\n"
  16. Fname = "data.dat"
  17. newFname = d2 + Fname
  18. return newFname
  19. print ObtainDate() # 2003-07-15data.dat
Last edited by flebber; Sep 26th, 2009 at 12:37 pm. Reason: tired
Reputation Points: 10
Solved Threads: 3
Light Poster
flebber is offline Offline
37 posts
since Aug 2009
Sep 26th, 2009
0

Re: Using Datetime for user input

You can trap error details this way:
python Syntax (Toggle Plain Text)
  1. import datetime as dt
  2.  
  3. def ObtainDate():
  4. isValid=False
  5. while not isValid:
  6. userIn = raw_input("Type Date dd/mm/yy: ")
  7. try: # strptime throws an exception if the input doesn't match the pattern
  8. d1 = dt.datetime.strptime(userIn, "%d/%m/%y")
  9. isValid=True
  10. #Perhaps set another try here.
  11. print d1, type(d1) # 2003-07-15 00:00:00 <type 'datetime.datetime'>
  12. "convert datetime object to a 10 character string"
  13. d2 = str(d1)[:10]
  14. print d2, type(d2) # 2003-07-15 <type 'str'>
  15. except ValueError, what_error:
  16. print what_error
  17. print "Try again! dd/mm/yy\n"
  18. Fname = "data.dat"
  19. newFname = d2 + Fname
  20. return newFname
  21.  
  22. print ObtainDate() # 2003-07-15data.dat
Reputation Points: 625
Solved Threads: 211
Posting Virtuoso
Ene Uran is offline Offline
1,704 posts
since Aug 2005
Sep 26th, 2009
0

Re: Using Datetime for user input

Click to Expand / Collapse  Quote originally posted by Ene Uran ...
You can trap error details this way:
python Syntax (Toggle Plain Text)
  1. import datetime as dt
  2.  
  3. def ObtainDate():
  4. isValid=False
  5. while not isValid:
  6. userIn = raw_input("Type Date dd/mm/yy: ")
  7. try: # strptime throws an exception if the input doesn't match the pattern
  8. d1 = dt.datetime.strptime(userIn, "%d/%m/%y")
  9. isValid=True
  10. #Perhaps set another try here.
  11. print d1, type(d1) # 2003-07-15 00:00:00 <type 'datetime.datetime'>
  12. "convert datetime object to a 10 character string"
  13. d2 = str(d1)[:10]
  14. print d2, type(d2) # 2003-07-15 <type 'str'>
  15. except ValueError, what_error:
  16. print what_error
  17. print "Try again! dd/mm/yy\n"
  18. Fname = "data.dat"
  19. newFname = d2 + Fname
  20. return newFname
  21.  
  22. print ObtainDate() # 2003-07-15data.dat
Much neater than a nested exception
Reputation Points: 10
Solved Threads: 3
Light Poster
flebber is offline Offline
37 posts
since Aug 2009

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: How to extact the personal address from html document
Next Thread in Python Forum Timeline: Help with pythonw.exe crashing





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC