How to convert these char values to datetime format?
114 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Mohamed Nedal
el 19 de En. de 2020
Comentada: Stephen23
el 2 de Sept. de 2022
Hello everyone,
I tried to do this operation to get the duration between both datetimes as follows:
% starting date-time
date_obs = char('2017/09/06');
time_obs = char('11:55:01.109');
% ending date-time
date_end = char('2017/09/06');
time_end = char('12:10:01');
% combining dates & times
datetime_start = strcat(date_obs,{' '},time_obs);
datetime_end = strcat(date_end,{' '},time_end);
%% DATETIMES
datetime1 = datetime(datetime_start,'InputFormat','yyyy/MM/dd HH:mm:ss');
datetime2 = datetime(datetime_end,'InputFormat','yyyy/MM/dd HH:mm:ss');
But I get this error:
Unable to convert '2017/09/06 11:55:01.109' to datetime using the format 'yyyy/MM/dd HH:mm:ss'.
Can you please tell me how to convert them to datetime and get the difference (duration) between both?
I appreciate your help!
Thank you,
0 comentarios
Respuesta aceptada
Stephen23
el 19 de En. de 2020
Editada: Stephen23
el 19 de En. de 2020
The error is caused by the milliseconds in start string: either you need to remove them from the input string, or specify them in the Input format:
>> datetime1 = datetime(datetime_start,'InputFormat','yyyy/MM/dd HH:mm:ss.SSS')
datetime1 =
06-Sep-2017 11:55:01
It is not permitted to have unused characters left over, all characters must correspond to something in the format string. After that it is trivial to calculate the difference (and generate a duration object):
>> dtdiff = datetime2-datetime1
dtdiff =
00:14:59
3 comentarios
Patryk Sapiega
el 2 de Sept. de 2022
What will it look like in version 2014a where this feature is missing?
Stephen23
el 2 de Sept. de 2022
"What will it look like in version 2014a where this feature is missing?"
DATETIME was introduced in R2014b, so you would need to use deprecated date functions, e.g.:
N1 = datenum('2017/09/06 11:55:01.109','yyyy/m/d HH:MM:SS.FFF');
N2 = datenum('2017/09/06 12:10:01','yyyy/m/d HH:MM:SS');
DD = datestr(N2-N1,'HH:MM:SS.FFF')
Más respuestas (0)
Ver también
Categorías
Más información sobre Dates and Time en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!