Converting date difference to years in Julia

Viewed 234

Using Julia, I'd like the find the period between two points in time, t2 and t1, where both t1 and t2 are in the format "y-m-d". I'm able to get this value in days, but I'd like to covert it to years:

date_format = DateFormat("y-m-d")
age_days = Date(t2, date_format) - Date(t1, date_format)
age_years = Dates.Year(age_days)

The above consistently returns an error. Understand I could just do Dates.value(age_days)/365.25, but is there a way to do this utilizing a built in function?

1 Answers

This functionality can be found in DayCounts.jl:

julia> using Dates, DayCounts

julia> d1=Date("2020-02-14", dateformat"y-m-d");

julia> d2=Date("2021-02-15", dateformat"y-m-d");

julia> yearfrac(d1,d2,DayCounts.ActualActualISDA())
1.003069091997904

The tricky part is to decide what to use as numerator and denominator when calculating such values. The above code used 2006 ISDA definitions, §4.16 (b) approach:

(# of days in standard year)/365 + (# of days in leap year)/366

There are many other implementations and they all seem to be implemented in that library.

Note that this is an additional answer to my previous post: Julia/Dates : convert a timespan from "days" to "year" or "Float64" that may be a better match here.

Related