| | |
Using Datetime for user input
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved |
•
•
Join Date: Aug 2009
Posts: 10
Reputation:
Solved Threads: 1
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.
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)
from datetime import date def ObtainDate(): input = raw_input("Type Date dd/mm/year: ") d = datetime.strptime(input, "%y-%m-%d") print ObtainDate
Last edited by flebber; Sep 25th, 2009 at 9:02 pm.
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:
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:
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
PYTHON Syntax (Toggle Plain Text)
input = raw_input("Type Date dd/mm/year: ")
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)
import datetime def ObtainDate(): isValid=False while not isValid: userIn = raw_input("Type Date dd/mm/yy: ") try: # strptime throws an exception if the input doesn't match the pattern d = datetime.datetime.strptime(userIn, "%d/%m/%y") isValid=True except: print "Doh, try again!\n" return d #test the function 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!
Those who understand binary .....
And those who don't!
•
•
Join Date: Aug 2009
Posts: 10
Reputation:
Solved Threads: 1
•
•
•
•
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:
Change your variable 'input' to something like 'userInput' or just anything that isn't a reserved word and you will get your prompt!PYTHON Syntax (Toggle Plain Text)
input = raw_input("Type Date dd/mm/year: ")
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)
import datetime def ObtainDate(): isValid=False while not isValid: userIn = raw_input("Type Date dd/mm/yy: ") try: # strptime throws an exception if the input doesn't match the pattern d = datetime.datetime.strptime(userIn, "%d/%m/%y") isValid=True except: print "Doh, try again!\n" return d #test the function 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
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.
•
•
•
•
Awesome I like it just one question why does the line below have datetime twice?
d = datetime.datetime.strptime(userIn, "%d/%m/%y")
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)
import datetime as dt
PYTHON Syntax (Toggle Plain Text)
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!
Those who understand binary .....
And those who don't!
To find the error class simply create the error ...
Also be aware that d1 will be a datetime object and not a string, so you have to do some simple extra coding ...
This file name should sort well.
python Syntax (Toggle Plain Text)
import datetime as dt # the date has to be entered in dd/mm/yy format # entering dd/mm/yyyy by mistake will create an error # the error class will be --> ValueError test_date = "15/07/2003" d1 = dt.datetime.strptime(test_date, "%d/%m/%y")
python Syntax (Toggle Plain Text)
import datetime as dt # date has been entered in dd/mm/yy format test_date = "15/07/03" d1 = dt.datetime.strptime(test_date, "%d/%m/%y") print d1, type(d1) # 2003-07-15 00:00:00 <type 'datetime.datetime'> # convert datetime object to a 10 character string d2 = str(d1)[:10] print d2, type(d2) # 2003-07-15 <type 'str'> # now you can use string d2 to create filenames fname = "data.dat" new_fname = d2 + fname print new_fname # 2003-07-15data.dat
Last edited by vegaseat; Sep 26th, 2009 at 10:04 am.
May 'the Google' be with you!
•
•
Join Date: Aug 2009
Posts: 10
Reputation:
Solved Threads: 1
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.
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)
mport datetime as dt def ObtainDate(): isValid=False while not isValid: userIn = raw_input("Type Date dd/mm/yy: ") try: # strptime throws an exception if the input doesn't match the pattern d1 = dt.datetime.strptime(userIn, "%d/%m/%y") isValid=True #Perhaps set another try here. print d1, type(d1) # 2003-07-15 00:00:00 <type 'datetime.datetime'> "convert datetime object to a 10 character string" d2 = str(d1)[:10] print d2, type(d2) # 2003-07-15 <type 'str'> except: print "Try again! dd/mm/yy\n" Fname = "data.dat" newFname = d2 + Fname return newFname print ObtainDate() # 2003-07-15data.dat
Last edited by flebber; Sep 26th, 2009 at 12:37 pm. Reason: tired
You can trap error details this way:
python Syntax (Toggle Plain Text)
import datetime as dt def ObtainDate(): isValid=False while not isValid: userIn = raw_input("Type Date dd/mm/yy: ") try: # strptime throws an exception if the input doesn't match the pattern d1 = dt.datetime.strptime(userIn, "%d/%m/%y") isValid=True #Perhaps set another try here. print d1, type(d1) # 2003-07-15 00:00:00 <type 'datetime.datetime'> "convert datetime object to a 10 character string" d2 = str(d1)[:10] print d2, type(d2) # 2003-07-15 <type 'str'> except ValueError, what_error: print what_error print "Try again! dd/mm/yy\n" Fname = "data.dat" newFname = d2 + Fname return newFname print ObtainDate() # 2003-07-15data.dat
drink her pretty
•
•
Join Date: Aug 2009
Posts: 10
Reputation:
Solved Threads: 1
•
•
•
•
You can trap error details this way:
python Syntax (Toggle Plain Text)
import datetime as dt def ObtainDate(): isValid=False while not isValid: userIn = raw_input("Type Date dd/mm/yy: ") try: # strptime throws an exception if the input doesn't match the pattern d1 = dt.datetime.strptime(userIn, "%d/%m/%y") isValid=True #Perhaps set another try here. print d1, type(d1) # 2003-07-15 00:00:00 <type 'datetime.datetime'> "convert datetime object to a 10 character string" d2 = str(d1)[:10] print d2, type(d2) # 2003-07-15 <type 'str'> except ValueError, what_error: print what_error print "Try again! dd/mm/yy\n" Fname = "data.dat" newFname = d2 + Fname return newFname print ObtainDate() # 2003-07-15data.dat
![]() |
Similar Threads
- user input into a string (C++)
- Tutorial: User Input: Strings and Numbers [C] (C)
- Handling Invalid User Input? (C)
- inline assembly getting user input.(djgpp) (Assembly)
- Type Conversion of User Input: (C++)
- Error Checking for user input (Java)
- error checking of user input (C++)
- Creating a GUI that accepts user input help (Java)
- Need Help With Error Checking User Input (C)
- filtering bad user input (Java)
Other Threads in the Python Forum
- Previous Thread: How to extact the personal address from html document
- Next Thread: Help with pythonw.exe crashing
| Thread Tools | Search this Thread |
abrupt ansi anti apache approximation array assignment backend beginner binary book builtin calculator chmod code converter countpasswordentry curved customdialog dan08 dictionaries dictionary drive dynamic examples excel file filename float format function gui heads homework import inches input java launcher library line lines linux list lists loop mouse mysql mysqlquery number numbers numeric output parsing path phonebook plugin pointer port prime programming progressbar projects py2exe pygame pysimplewizard python random recursion redirect scrolledtext software statictext statistics string strings sum table terminal text textarea thread threading time tkinter tlapse trick tricks tuple tutorial twoup ubuntu unicode urllib urllib2 variable windows wordgame write wxpython






