Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何转换日期时间_Python_Python 2.7_Datetime - Fatal编程技术网

Python 如何转换日期时间

Python 如何转换日期时间,python,python-2.7,datetime,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_nam

我有以下代码:

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()
从日期时间导入*
姓氏=“”
first_name=“”
出生日期=“”
昵称=“”
类人(对象):
定义初始(自我、姓氏、名字、出生日期、昵称=无):
self.姓氏=姓氏
self.first\u name=first\u name
self.birth\u date=datetime.strtime(出生日期,%Y-%m-%d”).date()
self.昵称=昵称
如果self.昵称为None:
self.昵称=self.姓氏
def获取年龄(自我):
今天=日期。今天()
年龄=今天.year-self.birth\u date.year
如果今天.month
打印petroff.birth\u日期给我字符串“1952-01-02” 如何更改我的代码,以获取petroff.birth\u date=>datetime的值。date(1952,1,2)

根据,
\u str\u
(被
print
调用以获取对象的可打印视图)将
日期()的内容转换为字符串“1952-01-02”。您仍然可以根据需要比较
date()
对象。

相关: