Linspace with DateTime

I wanted to create a linearly spaced range of DateTimes, but:

julia> linspace(DateTime(0), now(), 5)
5-element LinSpace{DateTime}:
Error showing value of type LinSpace{DateTime}:
ERROR: MethodError: no method matching *(::Float64, ::DateTime)

So I wrote this:

function mylinspace(d1::DateTime, d2::DateTime, n::Int)
    Δ = d2 - d1
    T = typeof(Δ)
    δ = T(round(Int, Dates.value(Δ)/(n - 1)))
    d2 = d1 + δ*(n - 1)
    return d1:δ:d2
end

which works:

julia> mylinspace(DateTime(0), now(), 5)
0000-01-01T00:00:00:15919946730059 milliseconds:2017-12-06T13:42:00.236

Obviously, this is slightly off but its accuracy is on the order of a few milliseconds, which I can live with.

2 Likes