如何将datetime对象作为参数传递给类?

时间:2018-11-27 19:50:38

标签: python oop datetime types

我是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

1 个答案:

答案 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