Pythonic difference between two dates in years?

后端 未结 12 2512
醉酒成梦
醉酒成梦 2020-12-02 16:21

Is there a more efficient way of doing this below? I want to have the difference in years between two dates as a single scalar. Any suggestions are welcome.

         


        
12条回答
  •  青春惊慌失措
    2020-12-02 17:16

    I use one of these to calculate person's age:

    import datetime
    dob = datetime.date(1980, 10, 10)
    
    def age():
        today = datetime.date.today()
        years = today.year - dob.year
        if today.month < dob.month or (today.month == dob.month and today.day < dob.day):
            years -= 1
        return years
    
    def age2():
        today = datetime.date.today()
        this_year_birthday = datetime.date(today.year, dob.month, dob.day)
        if this_year_birthday < today:
            years = today.year - dob.year
        else:
            years = today.year - dob.year - 1
        return years
    

提交回复
热议问题