7
$\begingroup$

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

$\endgroup$
1
  • $\begingroup$ Do you actually want rounding (up and down) or do you always want to round up (ceiling function?) $\endgroup$ Commented Nov 13, 2023 at 8:54

2 Answers 2

6
$\begingroup$

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
*)

```
$\endgroup$
1
  • $\begingroup$ While op said round, his example looks like he actually wants Ceiling (06:52:24 should be 07:00) $\endgroup$ Commented Nov 13, 2023 at 8:52
5
$\begingroup$
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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.