I am looking for a way to convert datetime objects to decimal(/float) year, including fractional part. 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. By decimal format I mean the float value 2007.4523
, where the fractional part is the number of seconds from the beginning of the year (2007-01-01 till 2007-04-14), divided by the total number of seconds in that year (2007-01-01 till 2008-01-01).
(NOTE: in statistical modeling (e.g. for linear regression), this is called "time index")
There is two methods: float_number = float ( decimal_number ) float_number = decimal_number * 1.0.
The DateTime value is then converted to a date value using the dt. date() function.
strftime() Function to Format Date to YYYYMMDD in Python. The strftime() is used to convert a datetime object to a string with a given format. We can specify the format for YYYY-MM-DD in the function as %Y-%m-%d . Note that this function returns the date as a string.
A float is a data type composed of a number that is not an integer, because it includes a fraction represented in decimal format.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With