How to convert these char values to datetime format?

160 次查看(过去 30 天)
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,

采纳的回答

Stephen23
Stephen23 2020-1-19
编辑:Stephen23 2020-1-19
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 个评论
Patryk Sapiega
Patryk Sapiega 2022-9-2
What will it look like in version 2014a where this feature is missing?
Stephen23
Stephen23 2022-9-2
"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')
DD = '00:14:59.891'

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by