How to add seconds to a HH:mm DateTime array ?

120 次查看(过去 30 天)
How do I add seconds as: ss = 00 to a datetime array of the form MM/dd/YYYY HH:mm: 04/15/2016 01:00 as an example
  1 个评论
Douglas Leaffer
Douglas Leaffer 2023-6-6
Thank you. Seems I was able to simply click on the timetable in the workspace and then in the Editor window, select (highlight) the column of datetime, then in thwe View tab in the menu select Date/Time Format MM/dd/yyyy HH:mm:ss and MATLAB added :00 seconds to each time row, which is what I needed. Regards

请先登录,再进行评论。

回答(3 个)

Nikhil
Nikhil 2023-6-6
Hello Douglas,
Try this:
% Original datetime array
datetimeArray = datetime('04/15/2016 01:00', 'InputFormat', 'MM/dd/yyyy HH:mm');
% Create an array of seconds (all zeros in this case)
secondsArray = seconds(zeros(size(datetimeArray)));
% Add the seconds to the datetime array
datetimeArrayWithSeconds = datetimeArray + secondsArray;

Les Beckham
Les Beckham 2023-6-6
datetime objects always have a seconds field. If you don't set it, it will already be zero by default, so you don't need to "add" anything. Also, Matlab displays the seconds by default. See example below.
datetimeArray = datetime('04/15/2016 01:00', 'InputFormat', 'MM/dd/yyyy HH:mm')
datetimeArray = datetime
15-Apr-2016 01:00:00
datetimeArray.Format
ans = 'dd-MMM-uuuu HH:mm:ss'

Steven Lord
Steven Lord 2023-6-6
Do you want to actually add seconds to the value (changing the time) or do you want to add seconds to the display (leaving the time alone)? Let's create some sample data.
dt = datetime('now') % Default display format includes seconds
dt = datetime
06-Jun-2023 18:57:30
dt.Format = 'MM/dd/yyyy HH:mm' % Change the format so seconds aren't included
dt = datetime
06/06/2023 18:57
We can add seconds to the time, making the new value not the same as the previous value
dt2 = dt + seconds(30) % change the value
dt2 = datetime
06/06/2023 18:58
dt2 == dt % false
ans = logical
0
Or we can add seconds to the display, leaving the new value the same as the previous value.
dt3 = dt
dt3 = datetime
06/06/2023 18:57
dt3.Format = dt3.Format + ":ss" % Change the display format to include seconds again
dt3 = datetime
06/06/2023 18:57:30
dt3 == dt % true
ans = logical
1

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by