7

I have a TimeObject for 06:52:24, and I'd like to round it to the nearest 15 minutes (in this case 07:00). Is this possible to do in general? I know how to do it manually, by getting the hour part and then rounding the minutes, but I'm hoping to generalize it to any interval

Adar Maori
  • 71
  • 1

2 Answers2

6

Use AbsoluteTime to convert date to seconds since January 1, 1900. Then round to nearest multiple of 15*60 seconds. Convert to a DateObject and get just the time by converting to a TimeObject and dropping the time zone with Most:

nearest15[t_] :=
 Module[{abs = AbsoluteTime@t },

Round[abs, 15*60] // DateObject // TimeObject // Most

]

test inputs:

t = TimeObject[{6, 52, 24}];
nearest15[t]

(06:45:00)

Works with both TimeObject and DateObject inputs:

SeedRandom[1234];
rt = RandomTime[]
rd = RandomDate[]

(*"21:02:18

Mon 10 Jul 2023 12:24:24GMT-5 *)

nearest15[rt] nearest15[rd]

(*" 21:00:00

12:30:00 *)

```

ydd
  • 3,673
  • 1
  • 5
  • 17
5
roundTimeObject[minutes_ : 15] := 
  TimeObject[Drop[DateList@Round[AbsoluteTime[#], 60 minutes], 3]] &;

Examples:

{t1, t2, t3} = {TimeObject[{6, 52, 24}], 
   TimeObject[{6, 55, 24}], TimeObject[{6, 23, 10}]};

Round t1, t2 and t3 to nearest multiples of 15 minutes, 10 minutes and 15 seconds:

Grid[
 Prepend[{"t", "roundTimeObject[]@t",
    "roundTimeObject[10]@t", "roundTimeObject[1/4]@t"}]@
 Map[{#, roundTimeObject[]@#, roundTimeObject[10]@#, roundTimeObject[1/4]@#} &]@
 {t1, t2, t3}, 
 Dividers -> All] 

enter image description here

kglr
  • 394,356
  • 18
  • 477
  • 896