Im currently doing a program in which stores user information such as their forename, surname and birth date. I'm not very experienced with advanced python functions and I've tried declaring the Birth date as a string value, but this leads to issues where literally any input can be provided, such as "24/05/98" or "24/05/1998".
How can i make the input only work with the format "DD/MM/YYYY"?
In general, it's not a great idea to let the user input structured data like this where "literally any input can be provided".
But the python-dateutil
package does a good job trying to accommodate.
from dateutil import parser
s1 = "24/05/98"
s2 = "24/05/1998"
s3 = "05/24/1998"
dt1 = parser.parse(s1)
dt2 = parser.parse(s2)
dt3 = parser.parse(s3)
print dt1 # 1998-05-24 00:00:00
print dt2 # 1998-05-24 00:00:00
print dt3 # 1998-05-24 00:00:00
print dt1 == dt2 # True
print dt1 == dt3 # True
Obviously, this niceness breaks down when it can't figure out the input, for example what order the month and date are in the string:
s4 = "1/2/15" # Feb 1, 2015 in D/M/Y
s5 = "2/1/15" # Feb 1, 2015 in M/D/Y
dt4 = parser.parse(s4)
dt5 = parser.parse(s5)
print dt4 # 2015-01-02 00:00:00
print dt5 # 2015-02-01 00:00:00
print dt4 == dt5 # False
Edit: Per your comment, if you know the format of the data, you can use strptime
.
If the input cannot be parsed successfully, given the pattern you provide (in this case, %d/%m/%Y
or DD/MM/YYYY
), a ValueError
will be raised.
from datetime import datetime
s1 = "24/05/1998"
s2 = "05/24/1998"
s3 = "24/05/98"
for s in [s1, s2, s3]:
try:
dt = datetime.strptime(s, "%d/%m/%Y")
print(dt)
except ValueError:
print("Failed to parse: %s" % s)
Output:
1998-05-24 00:00:00 # Parse successful -- dt contains the datetime object Failed to parse: 05/24/1998 # Parse failed Failed to parse: 24/05/98 # Parse failed
Try this code, i hope it will solve your problem.
from time import strptime
date = raw_input("Please enter a date in DD/MM/YYYY format: ")
try:
parsed = strptime(date, "%d/%m/%Y")
except ValueError as e:
print "Please retry: {0}".format(e)
#Do your work...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.