Pythonic difference between two dates in years?

后端 未结 12 2495
醉酒成梦
醉酒成梦 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:11

    Here's a spin off of what Kostyantyn posted in his "age2" function. It's slightly shorter/cleaner and uses the traditional/colloquial meaning of an "age" or difference in years as well:

    def ageInYears( d ):
        today = datetime.date.today()
        currentYrAnniversary = datetime.date( today.year, d.month, d.day )
        return (today.year - d.year) - (1 if today < currentYrAnniversary else 0)
    

提交回复
热议问题