Interpolate Dates

Similar to this, I am interested in writing an interpolation for Date(Times).

julia> using Interpolations

julia> dates = [Dates.today()+Dates.Year(i-1) for i in 1:6]
6-element Array{Date,1}:
 2018-01-01
 2019-01-01
 2020-01-01
 2021-01-01
 2022-01-01
 2023-01-01

julia> values = [Float64(i-1) for i in 1:6]
6-element Array{Float64,1}:
 0.0
 1.0
 2.0
 3.0
 4.0
 5.0

julia> int = interpolate((dates,),values,Gridded(Linear()));

julia> int[Dates.today()+Dates.Month(6)]
ERROR: MethodError: no method matching length(::Date)
Closest candidates are:
  length(::SimpleVector) at essentials.jl:256
  length(::Base.MethodList) at reflection.jl:558
  length(::MethodTable) at reflection.jl:634
  ...
Stacktrace:
 [1] getindex(::Interpolations.GriddedInterpolation{Float64,1,Float64,Interpolations.Gridded{Interpolations.Linear},Tuple{Array{Date,1}},0}, ::Date) at C:\Users\Eric\.julia\v0.6\Interpolations\src\gridded\indexing.jl:96

Any ideas? :sweat_smile:

Looks like it’s mainly because length(::Date) isn’t defined. You could do eval(Base, :(length(::Date) = 1)) and see how far you get after that. If that’s all that’s needed, we could add that definition to stdlib/Dates, since I think we define that for Numbers anyway.

Numbers are iterable though. Maybe that makes a difference.

I am also interested in interpolation with DateTime as the x-variable.

using Interpolations, Dates

a = [DateTime(2018,1,1)+Hour(j) for j in 1:6]
println(a)

y = [3*j+1 for j in 1:6]

myinterp = LinearInterpolation(a, y)

ERROR: MethodError: no method matching (::Interpolations.Extrapolation{Float64,1,Interpolations.GriddedInterpolation{Float64,1,Int64,Gridded{Linear},Tuple{Array{DateTime,1}}},Gridded{Linear},Throw{Nothing}})(::DateTime)
Use square brackets for indexing an Array.

To solve your immidiate problem, you can:

julia> a2 = Dates.value.(a .- DateTime(2018,1,1))
6-element Vector{Int64}:
  3600000
  7200000
 10800000
 14400000
 18000000
 21600000

julia> myinterp = LinearInterpolation(a2, y)

which works.

But yeah, it would be good to either have this info somewhere visible or be able to interpolate date-times somehow.

1 Like

Thanks!

I guess there should be a layer which maps DateTime to number if DateTime is detected.