How to convert these char values to datetime format?

108 ビュー (過去 30 日間)
Mohamed Nedal
Mohamed Nedal 2020 年 1 月 19 日
コメント済み: Stephen23 2022 年 9 月 2 日
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 Center および File ExchangeDates and Time についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by