如何转换日期时间

时间:2015-03-21 07:37:14

标签: python python-2.7 datetime

我有这段代码:

from datetime import *
surname = ""
first_name = ""
birth_date = ""
nickname = ""
class Person(object):
    def __init__(self, surname, first_name, birth_date, nickname=None):
        self.surname = surname
        self.first_name = first_name
        self.birth_date = datetime.strptime(birth_date, "%Y-%m-%d").date()
        self.nickname = nickname
        if self.nickname is None :
            self.nickname = self.surname

    def get_age(self):
        today = date.today()
        age = today.year - self.birth_date.year
        if today.month < self.birth_date.month:
            age -= 1
        elif today.month == self.birth_date.month and today.day < self.birth_date.day:
            age -= 1
        return str(age)
    def get_fullname(self):
        return self.surname + " " + self.first_name

petroff = Person("Petrov", "Petro", "1952-01-02")
print petroff.surname
print petroff.first_name
print petroff.nickname
print petroff.birth_date
print petroff.get_fullname()
print petroff.get_age()

print petroff.birth_date给我字符串&#34; 1952-01-02&#34; 如何更改我的代码,获取petroff.birth_date =&gt;的值datetime.date(1952,1,2)

1 个答案:

答案 0 :(得分:0)

根据datetime documentation__str__(由print调用以获取对象的可打印视图)将date()的内容转换为字符串“1952- 01-02" 。您仍然可以根据需要比较date()个对象。