简体   繁体   中英

Unable to convert string to date in Python

from datetime import date


class student:
     def __init__ (self, firstname, lastname, number, birth):
         self.firstname = str(firstname)
         self.lastname = str(lastname)
         self.number = int(number)
         self.birthdate = date.fromisoformat(birth)
         self.note = int(0)
         self.kurs = str()

     def __repr__ (self):
         return '{firstname:' + str (self.firstname) + ', lastname:' \
                + str (self.lastname) + ',' 'number:' \
                + self.number + ',' 'birth:' \
                + self.birthdate + '}'

     def grade_entry (self):
         input ("coursename:")
         input ("coursegrade:")


     def put_entry(self):
         print(student.grade_entry())



o = student ('My', 'Name', '123456', '01-01-2000')
print(o)
student.grade_entry()
student.put_entry()

The following is wrong i cant resolve it i hope one person can help me.

AttributeError: type object 'datetime.date' has no attribute 'fromisoformat'

By the way can you tell me something. So if I write a few course names in def grade_entry , he should give it to me in the next function

This happens because you are using date.fromisoformat but '01-01-2000' is not of this format.


The following will work:

import datetime


self.birthdate = datetime.datetime.strptime(birth, '%d-%m-%Y').date()

On another note, your __repr__ is also wrong. Make sure to cast self.number and self.birthdate (ie str(self.number) and str(self.birthdate) ):

 def __repr__ (self):
     return '{firstname:' + str(self.firstname) + ', lastname:' \
            + str(self.lastname) + ',' 'number:' \
            + str(self.number) + ',' 'birth:' \
            + str(self.birthdate) + '}'

Finally, you are incorrectly calling the class instead of the created instance.

Instead of

o = student ('My', 'Name', '123456', '01-01-2000')
print(o)
student.grade_entry()
student.put_entry()

you should use:

o = student ('My', 'Name', '123456', '01-01-2000')
print(o)
o.grade_entry()
o.put_entry()

Also, put_entry should call self.grade_entry() instead of student.grade_entry() .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM