我是Python类的新手。我想将日期时间对象作为Person
传递给birth_date
类。
这就是我现在拥有的:
import datetime
class Person:
def __init__(self, first_name, last_name, birth_date):
self.first_name = first_name
self.last_name = last_name
def fullname(self):
return self.first + ' ' + self.last_name
答案 0 :(得分:1)
You can use datetime.strptime()
:
from datetime import datetime
class Person:
def __init__(self, first_name, last_name, birth_date):
self.first_name = first_name
self.last_name = last_name
self.birth_date = datetime.strptime(birth_date, '%b %d %Y')
def fullname(self):
return self.first + ' ' + self.last_name
person = Person('John', 'Doe', 'Jun 1 2005')
print(person.birth_date)
Returns:
2005-06-01 00:00:00
You assumed a particular date format, which you can modify as you see fit. Reference to docs here。