1

I am struggling to find the best way to convert the date input given by the user as mm/dd/yyyy to 3 variables. I am unable to split this because I receive an error since it is a 'float'.

>>> date=3/2/2016
>>> date.split('/')
Traceback (most recent call last):
  File "<pyshell#152>", line 1, in <module> date.split('/')
AttributeError: 'float' object has no attribute 'split'

what do I need to add to this to make sure it doesn't evaluate the date with division?

def main():
    date=input("Enter date mm/dd/yyyy: ") 

I want the input date given as mm/dd/yyyy, and then a way to convert this to 3 variables as m=month d=day y=year

What's the best way to do this?

jfs
  • 399,953
  • 195
  • 994
  • 1,670
Jessica Smith
  • 63
  • 1
  • 4
  • 1
    I don't understand your input data or your error message. Please provide a sample. – TigerhawkT3 May 13 '16 at 02:08
  • >>> date=3/2/2016 >>> date.split('/') Traceback (most recent call last): File "", line 1, in date.split('/') AttributeError: 'float' object has no attribute 'split' >>> – Jessica Smith May 13 '16 at 02:09
  • i believe it should be date='3/2/2016' The problem is that python is doing divides and creating the float 0.000744047619047619 instead of inputting as a string – user1462442 May 13 '16 at 02:12
  • def main(): date=input("Enter date mm/dd/yyyy: ") – Jessica Smith May 13 '16 at 02:17
  • what do I need to add to this to make sure it doesn't evaluate the date with division? – Jessica Smith May 13 '16 at 02:17
  • 1
    You need to learn about [the differences between the basic data types in Python (notably, strings and numbers)](https://docs.python.org/3.4/tutorial/introduction.html#using-python-as-a-calculator). – TigerhawkT3 May 13 '16 at 02:20

4 Answers4

2

Try str.split:

>>> test_date = "05/12/2016"
>>> month, day, year = test_date.split('/')
>>> print(f"Month = {month}, Day = {day}, Year = {year}")
Month = 05, Day = 12, Year = 2016
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
0

I wrote this following piece of code and it works perfectly fine.

>>> date='3/2/2016'
>>> new=date.split('/')
>>> new
['3', '2', '2016']
>>> 
>>> m,d,year=new
>>> m
'3'
>>> d
'2'
>>> year
'2016'
>>> 

Like Jessica Smith has already pointed it out, date=3/2/2016 evaluates expressions and divides the numbers. It has to be of string string type to be split.

Annapoornima Koppad
  • 1,376
  • 1
  • 17
  • 30
0

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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
-1

Try:

def main():
    month, day, year = [int(x) for x in raw_input("Enter date mm/dd/yyyy: ").split('/')]
    print "Month: {}\n".format(month), "Day: {}\n".format(day), "Year: {}".format(year)

main()

Output:

Enter date mm/dd/yyyy: 03/09/1987
Month: 3
Day: 9
Year: 1987
Andrés Pérez-Albela H.
  • 4,003
  • 1
  • 18
  • 29