Round down to a chosen hour-min-sec time at a date

8 views (last 30 days)
Hello,
I use
now_time = datetime(now,'ConvertFrom','datenum')
Assume it gives me
ans =
datetime
14-May-2019 02:28:24
Then assume I have some chosen time settings hh:mm:ss, eg:
A = [ 02:00:00 18:00:00 08:00:00 ]
I would like something to go back to the nearest time from my settings, in this case it should give me this (due to above now_time):
14-May-2019 02:00:00
If the now_time was 14-May-2019 01:59:59, then due to its before 02:00:00, I would like it to go to the time backwards "round down":
13-May-2019 18:00:00
Another example: Or if now_time is 13-May-2019 08:00:01
I would like:
13-May-2019 08:00:00
Hope I am clear enourgh and hope for some advise. Thanks in advance

Answers (2)

Walter Roberson
Walter Roberson on 14 May 2019
B = dateshift(now_time, 'start', 'day') + A_in_duration_form;
interp1(B, B, now_time, 'prev')
  5 Comments
Martin
Martin on 14 May 2019
Edited: Martin on 14 May 2019
Hi thanks for getting back.. It is always chronologically, so e.g. 14-Mar 02:00:00, 14-Mar 08:00:00, 14-Mar 18:00:00, 15-Mar 02:00:00. or 14-Mar 18:00:00 15-Mar 02:00:00, 15-Mar 08:00:00, 15-Mar 18:00:00
I ran it now, here 14-May, and the results gave me this:
now_time = datetime(now,'ConvertFrom','datenum')
A = [ hours(01) hours(07) hours(13) hours(19) ];
B = dateshift(now_time, 'start', 'day') + A;
B = [B-days(1), B];
interp1(B, B, now_time, 'prev')
now_time =
datetime
14-May-2019 23:14:17
ans =
datetime
NaT
In this case I would wish for the:
ans =
datetime
14-May-2019 19:00:00

Sign in to comment.


Peter Perkins
Peter Perkins on 4 Jun 2019
Since you're working in liear time (preserving dates) and no in circular time (caring only about time of day), I would think discretize would be a good way to do this:
>> dt = datetime('today') + hours(sort(48*rand(10,1)))
dt =
10×1 datetime array
04-Jun-2019 01:48:41
04-Jun-2019 04:44:17
04-Jun-2019 12:34:11
04-Jun-2019 17:38:13
04-Jun-2019 18:59:05
05-Jun-2019 08:35:54
05-Jun-2019 14:13:00
05-Jun-2019 18:29:17
05-Jun-2019 19:50:15
05-Jun-2019 23:25:23
>> bins = datetime(2019,6,[4 4 4 4 5 5 5 5],[0 2 8 18 2 8 18 24],0,0)
bins =
1×8 datetime array
Columns 1 through 5
04-Jun-2019 00:00:00 04-Jun-2019 02:00:00 04-Jun-2019 08:00:00 04-Jun-2019 18:00:00 05-Jun-2019 02:00:00
Columns 6 through 8
05-Jun-2019 08:00:00 05-Jun-2019 18:00:00 06-Jun-2019 00:00:00
>> discretize(dt,bins,bins(1:end-1))
ans =
10×1 datetime array
04-Jun-2019 00:00:00
04-Jun-2019 02:00:00
04-Jun-2019 08:00:00
04-Jun-2019 08:00:00
04-Jun-2019 18:00:00
05-Jun-2019 08:00:00
05-Jun-2019 08:00:00
05-Jun-2019 18:00:00
05-Jun-2019 18:00:00
05-Jun-2019 18:00:00

Categories

Find more on Dates and Time in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by