How to convert Python datetime dates to decimal/float years

前端 未结 7 1365
感动是毒
感动是毒 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:16
    from datetime import datetime as dt
    import time
    
    def toYearFraction(date):
        def sinceEpoch(date): # returns seconds since epoch
            return time.mktime(date.timetuple())
        s = sinceEpoch
    
        year = date.year
        startOfThisYear = dt(year=year, month=1, day=1)
        startOfNextYear = dt(year=year+1, month=1, day=1)
    
        yearElapsed = s(date) - s(startOfThisYear)
        yearDuration = s(startOfNextYear) - s(startOfThisYear)
        fraction = yearElapsed/yearDuration
    
        return date.year + fraction
    

    Demo:

    >>> toYearFraction(dt.today())
    2011.47447514
    

    This method is probably accurate to within the second (or the hour if daylight savings or other strange regional things are in effect). It also works correctly during leapyears. If you need drastic resolution (such as due to changes in the Earth's rotation) you are better off querying a net service.

    0 讨论(0)
提交回复
热议问题