Converting units of time deltas

Let’s say I want to get the fractional hours elapsed between two times. I often have code that looks something like

function hours_elapsed(start, stop)
    millis = (stop - start).value
    return millis / (1000 * 60 * 60)
end

This seems nasty for two reasons:

  • Trusting start - stop to return a Millisecond and not some other period type seems dangerous. Maybe start and stop are some other datetime-like type where subtraction returns a Second, not a Millisecond.
  • The above snippet is quite a mouthful.

What’s the preferred way to convert some elapsed time to a fractional number of time units?

You can use Millisecond(stop-start) to be sure you have milliseconds. But that will fail if the period is not an integer number of milliseconds. Safer would be to use

function hours_elapsed(start, stop)
    nanos = Nanosecond(stop - start)
    return Dates.value(nanos) * 1e-9 / 3600
end

though maybe not optimal for precision? (and no less of a mouthful than your example)

1 Like

Couldn’t you use the functions: Dates.datetime2epochms and Dates.epochms2datetime ?

using Dates
stop = now()
start = now() - Minute(90)
round((stop - start), Minute)/Minute(60)

For comparisons,

round((stop - start), Minute)/Minute(60) < 2*Minute(60).value

Hi,

This is perhaps more a Dates.jl design question, but is there any reason Dates.jl cannot be extended to support fractional hours via e.g. Hour{Float64}. Currently,

julia> Hour{Float64}
ERROR: TypeError: in Type{...} expression, expected UnionAll, got Type{Hour}
Stacktrace:
 [1] top-level scope
   @ REPL[13]:1

Just curious how the community feels about something like this?

1 Like