char to num (of datetime)

i'd like to change char to a numeric value so i can add it to my matrix.
my code:
t = datetime('now','Format','ydMHHmm');
x_num = str2double(t);
result:
x_num = NaN
i'd appretiate the help

1 Comment

Have you consider storing the values in a table instead? (That way, different column can be of different classes).

Sign in to comment.

Answers (1)

datetime() does not output string, it itself is an independent data type.
t = datetime('now','Format','y/d/M HH:mm')
t = datetime
2022/11/10 08:39
If you want to convert it into a numerical value, you can use datenum (though it is not recommended as per the function documentation home page)
format long
datenum(t)
ans =
7.388053610059826e+05

1 Comment

Alternately, you could define how long "1" is in terms of dates and times and use datetime and duration arithmetic. For example if you want a change of 1 in the double values to which the dates and times are mapped to represent 1 day of difference in the dates and times:
t = datetime('now','Format','y/d/M HH:mm')
t = datetime
2022/11/10 13:21
c = datetime('December 25, 2022','Format','y/d/M HH:mm')
c = datetime
2022/25/12 00:00
delta = days(c-t);
fprintf("It is %f days until Christmas!\n", delta)
It is 74.443398 days until Christmas!
If you're counting by minutes:
delta2 = minutes(c-t);
fprintf("It is %f minutes until Christmas!\n", delta2)
It is 107198.493499 minutes until Christmas!
Let's double check. There are this many minutes in a day:
mpd = delta2/delta
mpd = 1440
which we can check:
minutesPerDay = minutes(days(1))
minutesPerDay = 1440
I second the suggestion of @Davide Masiello to store your data in a table, though if you have time-based data a timetable array may be a better fit.

Sign in to comment.

Categories

Asked:

Aya
on 11 Oct 2022

Commented:

on 11 Oct 2022

Community Treasure Hunt

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

Start Hunting!