Round Dates.Time variable

Hi,

I am trying to round two variables - say X and Y - of type Dates.Time. X has value 09:30:01.017, Y has value 09:59:59.103 and I would like to round them to 09:30:00.000 and 10:00:00.000. I have tried using floor and ceil, but I keep getting errors with Dates.Time variables. I would appreciate if someone could write down a simple example showcasing how to use them with similar DataTypes.

Thanks!

Like this?

julia> t = now()
2022-10-05T13:03:49.422

julia> floor(t, Dates.Minute)
2022-10-05T13:03:00

Yes, but t is a DateTime, not a Time. My variables are of type Time.

Could be a missing method, maybe. If no one replies, file an issue

2 Likes

Will do. The below works, but it is a bit rough:

Dates.floor(X::Dates.Time, P::Dates.Period) = floor(DateTime("$(today())T$(X)", "yyyy-mm-ddTHH:MM:SS.s"), P) |> Time;
Dates.ceil(X::Dates.Time, P::Dates.Period) = ceil(DateTime("$(today())T$(X)", "yyyy-mm-ddTHH:MM:SS.s"), P) |> Time;
1 Like

You could also write user functions based on:

using Dates

t0 = Time("09:30:01.017")
t1 = Time(Nanosecond(round(Int, t0.instant/Nanosecond(1e9))*1e9))
09:30:01

t3 = Time("09:59:59.503")
t4 = Time(Nanosecond(round(Int, t3.instant/Nanosecond(1e9))*1e9))
10:00:00

This seems better, I am just not sure whether something similar is already implemented under Dates. I will open an issue on the Julia GitHub page and link this post.

A proposal along the lines of @rafael.guerra
The round function has methods for some types of DateTime.
Perhaps there is something more specific and direct

round(dt::TimeType, p::Period, [r::RoundingMode]) -> TimeType    

  Return the Date or DateTime nearest to dt at resolution p. By    
  default (RoundNearestTiesUp), ties (e.g., rounding 9:30 to the   
  nearest hour) will be rounded up.
using Dates
t0=Time("09:30:01.534")
t3 = Time("09:59:59.503")
Time(Nanosecond(round(t0.instant, Dates.Second)))
Time(Nanosecond(round(t3.instant, Dates.Second)))
2 Likes