How to convert these char values to datetime format?

116 views (last 30 days)
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,

Accepted Answer

Stephen23
Stephen23 on 19 Jan 2020
Edited: Stephen23 on 19 Jan 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 Comments
Patryk Sapiega
Patryk Sapiega on 2 Sep 2022
What will it look like in version 2014a where this feature is missing?
Stephen23
Stephen23 on 2 Sep 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')
DD = '00:14:59.891'

Sign in to comment.

More Answers (0)

Categories

Find more on Dates and Time in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!