why does this not work?
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
>> x='0:07.50 2:03.91 3:57.36 5:09.44 6:32.90 7:43.03 9:43.45';
>> datetime(x,'InputFormat','m:ss.SS')
Error using datetime (line 257)
Unable to convert '0:07.50 2:03.91 3:57.36 5:09.44 6:32.90 7:43.03 9:43.45' to
datetime using the format 'm:ss.SS'.
0 commentaires
Réponse acceptée
Les Beckham
le 27 Mar 2025
Modifié(e) : Les Beckham
le 27 Mar 2025
That doesn't work because your x is one long character vector and datetime tries to match your input format to the entire contents of x. Instead define x as either a string array or a cell array of character vectors.
Using a string array:
x = [ "0:07.50" "2:03.91" "3:57.36" "5:09.44" "6:32.90" "7:43.03" "9:43.45" ];
dt1 = datetime(x,'InputFormat','m:ss.SS')
Using a cell array of char vectors:
x= { '0:07.50' '2:03.91' '3:57.36' '5:09.44' '6:32.90' '7:43.03' '9:43.45' };
dt2 = datetime(x,'InputFormat','m:ss.SS')
isequal(dt1, dt2)
Edit:
If you want to convert your datetime array to numeric seconds:
dt_seconds = 60*minute(dt1) + second(dt1)
0 commentaires
Plus de réponses (3)
John D'Errico
le 27 Mar 2025
It failed because datetime did not recognize that string as a list of distinct times. Just because you know what you want code to do, does not mean it will read your mind. Code is pretty dumb in general.
x='0:07.50 2:03.91 3:57.36 5:09.44 6:32.90 7:43.03 9:43.45';
xspl = strsplit(x,' ')
datetime(xspl,'InputFormat','m:ss.SS')
0 commentaires
Star Strider
le 27 Mar 2025
Modifié(e) : Star Strider
le 27 Mar 2025
need to separate the elements of the array (that I changed to a cell array here).
Then, it works —
x = {'0:07.50' '2:03.91' '3:57.36' '5:09.44' '6:32.90' '7:43.03' '9:43.45'};
datetime(x,'InputFormat','m:ss.SS')
.
EDIT — (27 Mar 2025 at 21:13)
Perhaps this —
x = {'0:07.50' '2:03.91' '3:57.36' '5:09.44' '6:32.90' '7:43.03' '9:43.45'};
dt = datetime(x,'InputFormat','m:ss.SS')
dtm = seconds(timeofday(dt))
This works, and there may also be other ways of doing that conversion.
.
0 commentaires
Rob
le 27 Mar 2025
Modifié(e) : Rob
le 27 Mar 2025
3 commentaires
Steven Lord
le 27 Mar 2025
Or you can create a duration instead of a datetime and avoid having to do the dateshift.
S = [ "0:07.50" "2:03.91" "3:57.36"];
DT = duration(S, "InputFormat", "mm:ss.SS")
D = seconds(DT)
Walter Roberson
le 27 Mar 2025
Ah, when I tested with duration, I missed that you need to use mm instead of m
Voir également
Catégories
En savoir plus sur Characters and Strings dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!