The error "'float' object has no attribute 'split'" suggests that type(date) == float
in your example that implies that you are trying to run Python 3 code using Python 2 interpreter where input()
evaluates its input as a Python expression instead of returning it as a string.
To get the date as a string on Python 2, use raw_input()
instead of input()
:
date_string = raw_input("Enter date mm/dd/yyyy: ")
To make it work on both Python 2 and 3, add at the top of your script:
try: # make input() and raw_input() to be synonyms
input = raw_input
except NameError: # Python 3
raw_input = input
If you need the old Python 2 input()
behavior; you could call eval()
explicitly.
To validate the input date, you could use datetime.strptime()
and catch ValueError
:
from datetime import datetime
try:
d = datetime.strptime(date_string, '%m/%d/%Y')
except ValueError:
print('wrong date string: {!r}'.format(date_string))
.strptime()
guarantees that the input date is valid otherwise ValueError
is raised. On success, d.year
, d.month
, d.day
work as expected.
Putting it all together (not tested):
#!/usr/bin/env python
from datetime import datetime
try: # make input() and raw_input() to be synonyms
input = raw_input
except NameError: # Python 3
raw_input = input
while True: # until a valid date is given
date_string = raw_input("Enter date mm/dd/yyyy: ")
try:
d = datetime.strptime(date_string, '%m/%d/%Y')
except ValueError: # invalid date
print('wrong date string: {!r}'.format(date_string))
else: # valid date
break
# use the datetime object here
print("Year: {date.year}, Month: {date.month}, Day: {date.day}".format(date=d))
See Asking the user for input until they give a valid response.
You could use .split('/')
instead of .strptime()
if you must:
month, day, year = map(int, date_string.split('/'))
It doesn't validate whether the values form a valid date in the Gregorian calendar.