How can I do a datetime vector?

61 views (last 30 days)
Marianna Pizzo
Marianna Pizzo on 25 Mar 2019
Edited: dpb on 25 Mar 2019
Hello, how can I do a datime vector. I have a vector whose name is T where I have date and time in this format : '03/19/2019 16:36:41', I want only the time so I write:
for(i=2:n)%I don't want the first row so I start from 2
a=T{i};
x(i,:)=a(11:end);
...
then I want to put every element of x (x is a matrix 1159x9) into a datetime vector so I do:
for (j=1:n-1)
H{j}=datetime(x(i,:),'Format','HH:mm:ss');
end
end
Matlab doesn't show any error but if I try to view H{34}, for example, it doesn't show me anything.
  1 Comment
dpb
dpb on 25 Mar 2019
>> t= '03/19/2019 16:36:41'; % your sample input form...
>> datetime(t(11:end))
ans =
datetime
25-Mar-2019 16:36:41
>>
shows that with datetime you simply cannot have just a time; there's always an implied date if not a specific one.
You can return arrays of the time components from a datetime array but you can't create the array in the beginning without a date being associated with the time. I, personally, tend to think this is an undesireable limitation as well, but it is what it is and I don't see TMW changing it.
Time-only vectors can only be some form of a duration; either calendar or absolute.
Your code not returning anything is an error don't see a cause for otomh, but you don't need a loop as datetime is vectorized for cell array of strings but you can't actually do what you're trying to do anyways...

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 25 Mar 2019
Just do something like this:
T = datetime('03/19/2019 16:36:41')
H = datetime(T,'Format','HH:mm:ss')
producing:
T =
datetime
19-Mar-2019 16:36:41
H =
datetime
16:36:41
  3 Comments
Star Strider
Star Strider on 25 Mar 2019
True for datetime arrays.
If you only want the time as a (1x8) character vector, do this:
H = datestr(T, 'hh:mm:ss')
producing:
H =
'16:03:41'
dpb
dpb on 25 Mar 2019
Yeah, I still don't understand TMW's thinking on forcing the date to exist instead of just letting one have an array of times if that's all one wants for a given task.
With the venerable datenum since it's just a double(), one can do so easily by throwing away the integer portion but it has all the other issues associated with it so it's not all that attractive of a solution, either.

Sign in to comment.

More Answers (0)

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!