How do I convert a string to a date?
Ältere Kommentare anzeigen
Currently I have the string:
2017-03-18 03:26:42.000000
I want to convert this to a date, and I use the following function:
datetime(my_string,'InputFormat','yyyy-mm-dd HH:MM:SS')
However, when I do this I get the following error:
Unable to parse '2017-03-18 03:26:42.000000' as a date/time using the format 'yyyy-mm-dd HH:MM:SS'.
I have also tried
datetime(my_string,'InputFormat','yyyy-mm-dd HH:MM:SSSSSSSSS')
and
datetime(my_string,'InputFormat','yyyy-mm-dd HH:MM:SS.SSSSSSS')
But none of these seem to work. How would I go about doing this?
Akzeptierte Antwort
Weitere Antworten (1)
Rik
am 17 Jul. 2017
It is a bit confusing, but the capital S only denotes the fraction of a second, so not the second itself. The code below works.
my_string='2017-03-18 03:26:42.000000';
datetime(my_string,'InputFormat','yyyy-MM-dd HH:mm:ss.SSSSSS')
5 Kommentare
Guillaume
am 17 Jul. 2017
Note that for decoding you only need one S regardless of the number of fractional digits. The number of S only affects the datetime display when it is part of the Format property
Rik
am 17 Jul. 2017
Good to know, thanks Guillaume.
Amini
am 3 Feb. 2022

thanks for your answers, I have to use the function datetime, actually I want to find the differences between timestamps. (for example: row 2 minuse row 1). the problem is two characters before the DAY 24 '[ and also the format of MONTH Sep. how should I use this function to approach this problem? thanks in advance. @Rik @Guillaume @Douglas Leaffer
Amini
am 3 Feb. 2022
in this way it works:
DateStrings = {'24/09/2021:10:56:23'};
t = datetime(DateStrings,'InputFormat','dd/MM/yyyy:HH:mm:ss')
But my date is 24/Sep/2021:10:56:23
and in this way it doesn't work
DateStrings = {'24/Sep/2021:10:56:23'};
t = datetime(DateStrings,'InputFormat','dd/MM/yyyy:HH:mm:ss')
%again, beside the problem of two extra characters
Amini
am 3 Feb. 2022
I found it how to eliminate the extra characters, using erase but still stacked with MONTH part
Kategorien
Mehr zu Dates and Time finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!