How to convert Python datetime dates to decimal/float years

前端 未结 7 1383
感动是毒
感动是毒 2020-12-09 18:18

I am looking for a way to convert datetime objects to decimal(/float) year, including fractional part. Example:

>>> obj = SomeObjet()
>>> o         


        
7条回答
  •  天涯浪人
    2020-12-09 19:06

    This is a little simpler way than the other solutions:

    import datetime
    def year_fraction(date):
        start = datetime.date(date.year, 1, 1).toordinal()
        year_length = datetime.date(date.year+1, 1, 1).toordinal() - start
        return date.year + float(date.toordinal() - start) / year_length
    
    >>> print year_fraction(datetime.datetime.today())
    2016.32513661
    

    Note that this calculates the fraction based on the start of the day, so December 31 will be 0.997, not 1.0.

提交回复
热议问题