Simple conversion from Time to Period?

I could do Time(12).instant, but that is probably not good practice. Doing Time(12) - Time(0) seems odd. Is there some proper way to convert Time to Period?

One thing that motivates this question is that I want to calculate the Period from a Time to the end of day. However, I cannot do Time(24) - Time(x) because the Time constructor will not allow 24 (out of range).

Perhaps you could do: typemax(Time) - Time(x)
or maybe:
(typemax(Time) - Time(x)) + Nanosecond(1)
if 1 ns matters.

Thanks! I didn’t know about typemax. That’s interesting.
That solution is interesting, but isn’t much better than Time(x).instant because it relies on (or reveals) the implementation details of Time (that it is stored in nanoseconds).

The more I think about it now, the more I think I just need to write my own Base.convert(Period, Time) and use Time.instant. If that ever changes, there’s only a single place to fix.

I was just asking if that conversion already existed somewhere and I just couldn’t find it.

It looks like something has been done for DateTime


t=(1,1,1)
julia> canonicalize(DateTime(t...,24, 0, 0)- DateTime(t...,17, 55, 30))
6 hours, 4 minutes, 30 seconds



julia> canonicalize(Hour(24)-(Hour(17)+Minute(44)+Second(30)))
6 hours, 15 minutes, 30 seconds

That’s curious. That only works if you have all zeros after the hour. DateTime(1,1,1,24,0,0,1) gives error. Putting that 24 in hours rolls it over to 0 time the next day. Interesting, but probably not helpful to what I’m trying to do.

I think I’ll just do something like:

Base.convert(::Type{Nanosecond}, t::Time) = t.instant
(Base.convert(::Type{T}, t::Time)::T) where T<:TimePeriod = convert(T, convert(Nanosecond, t))

Then calculating until end of day is something like: Day(1) - convert(Second, Time(12))

What about:

using Dates

dt = (typemax(Time) - Time(12,10,15)) + Nanosecond(1)
period = canonicalize(dt)

11 hours, 49 minutes, 45 seconds

I think that’s the same as the first suggestion above. It leaks the details of Time implementation. If I’m ok leaking that, I might as well just do Time(x).instant because that would also be the highest performing (which this may be used in some big loops so may matter).

It doesn’t leak anything if hermetically closed in a function.

Right, which is why I’ll just wrap Time(x).instant in a function.

That’s type piracy, isn’t it? Also, it doesn’t seem to make sense, converting time to period. It’s unsound.

Isn’t it better to create a custom function instead?

I thought the same thing after typing it but didn’t edit the post. I agree that doing a custom function is more appropriate.