user739807 user739807 - 1 year ago 340
Python Question

python how to convert datetime dates to decimal years

I am looking for a way to convert datetime objects to decimal year. Below is an example

>>> obj = SomeObjet()
>>> obj.DATE_OBS
datetime.datetime(2007, 4, 14, 11, 42, 50)

How do i convert datetime.datetime(2007, 4, 14, 11, 42, 50) to decimal years? From this format dd/mm/yyyy to this kind of format yyyy.yyyy

Answer Source
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


>>> toYearFraction(

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download