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
Asked
Active
Viewed 229 times
7
Adar Maori
- 71
- 1
-
Do you actually want rounding (up and down) or do you always want to round up (ceiling function?) – infinitezero Nov 13 '23 at 08:54
2 Answers
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
-
While op said round, his example looks like he actually wants
Ceiling(06:52:24 should be 07:00) – infinitezero Nov 13 '23 at 08:52
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]
kglr
- 394,356
- 18
- 477
- 896
