Using Datetime for user input

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Aug 2009
Posts: 10
Reputation: flebber is an unknown quantity at this point 
Solved Threads: 1
flebber flebber is offline Offline
Newbie Poster

Using Datetime for user input

 
0
  #1
Sep 25th, 2009
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.

  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.
Reply With Quote Quick reply to this message  
Join Date: Jan 2009
Posts: 337
Reputation: JasonHippy is just really nice JasonHippy is just really nice JasonHippy is just really nice JasonHippy is just really nice 
Solved Threads: 60
JasonHippy's Avatar
JasonHippy JasonHippy is offline Offline
Posting Whiz

Re: Using Datetime for user input

 
0
  #2
Sep 25th, 2009
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:
  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:
  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
There are 10 types of people in this world.....
Those who understand binary .....
And those who don't!
Reply With Quote Quick reply to this message  
Join Date: Aug 2009
Posts: 10
Reputation: flebber is an unknown quantity at this point 
Solved Threads: 1
flebber flebber is offline Offline
Newbie Poster

Re: Using Datetime for user input

 
0
  #3
Sep 26th, 2009
Originally Posted by JasonHippy View Post
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:
  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:
  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.
Reply With Quote Quick reply to this message  
Join Date: Jan 2009
Posts: 337
Reputation: JasonHippy is just really nice JasonHippy is just really nice JasonHippy is just really nice JasonHippy is just really nice 
Solved Threads: 60
JasonHippy's Avatar
JasonHippy JasonHippy is offline Offline
Posting Whiz

Re: Using Datetime for user input

 
0
  #4
Sep 26th, 2009
Originally Posted by flebber View Post
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:
  1. import datetime as dt
This gives the datetime package an alias (dt). So to call the strptime function I'd need to use:
  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.
There are 10 types of people in this world.....
Those who understand binary .....
And those who don't!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,070
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 938
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Using Datetime for user input

 
0
  #5
Sep 26th, 2009
To find the error class simply create the error ...
  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 ...
  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.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Aug 2009
Posts: 10
Reputation: flebber is an unknown quantity at this point 
Solved Threads: 1
flebber flebber is offline Offline
Newbie Poster

Re: Using Datetime for user input

 
0
  #6
Sep 26th, 2009
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.

  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
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,546
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 174
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Using Datetime for user input

 
0
  #7
Sep 26th, 2009
You can trap error details this way:
  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
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Aug 2009
Posts: 10
Reputation: flebber is an unknown quantity at this point 
Solved Threads: 1
flebber flebber is offline Offline
Newbie Poster

Re: Using Datetime for user input

 
0
  #8
Sep 26th, 2009
Originally Posted by Ene Uran View Post
You can trap error details this way:
  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
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC