I am looking for a way to convert datetime objects to decimal year. Below is an example
>>> obj = SomeObjet()
datetime.datetime(2007, 4, 14, 11, 42, 50)
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(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.