How to convert these char values to datetime format?
115 次查看(过去 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,
0 个评论
采纳的回答
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 个评论
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')
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Dates and Time 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!