MATLAB Answers

Can't get string to datetime conversion to work

조회 수: 1(최근 30일)
Nathan Heller
Nathan Heller 2021년 6월 11일
댓글: Nathan Heller 2021년 6월 12일
There seems to be some sort of inconsistency in the converting to datetime code I missed.
q=datetime('2017-05-17 19:36:00', 'InputFormat','yyyy-MM-dd HH:mm:ss')
this works just fine. However, when I am reading the input string '2017-05-17T19:36:00' from an array, stripping the T, and putting it in exactly the same, it fails to work. example:
%data{1}(n) has the string '2019-05-17T19:36:00'
b = strrep(data{1}(n),'T',' ');
%displaying displays 2017-05-17 19:36:00, just like the earlier statement
timestamp = datetime(b,'InputFormat',format);
When I do this, the error message:
Unable to convert '2017-05-17 19:36:00' to datetime using the format 'yyyy-MM-dd HH:mm:ss'.
is displayed. Am i missing something? are these not exactly the same? Thanks for your help.
  댓글 수: 2
Nathan Heller
Nathan Heller 2021년 6월 11일
here you go

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2021년 6월 11일
The very first entry in your data{1} has a leading U+FEFF character, which is a unicode Byte Order Mark character, but is to be interpreted as a Zero-Width Non-Breaking Space if it occurs anywhere other than the first position
  댓글 수: 3
Nathan Heller
Nathan Heller 2021년 6월 12일
Thanks for all your help!

댓글을 달려면 로그인하십시오.

추가 답변(1개)

J. Alex Lee
J. Alex Lee 2021년 6월 11일
str = '2019-05-17T19:36:00';
fmt = 'yyyy-MM-dd HH:mm:ss';
b = strrep(str,'T',' ');
2019-05-17 19:36:00
timestamp = datetime(b,'InputFormat',fmt)
timestamp = datetime
17-May-2019 19:36:00
Works for me ?
  댓글 수: 1
Nathan Heller
Nathan Heller 2021년 6월 11일
I still get the same error when i use your code with str = data {1}(n), so i assume there must be some problem with the data file?

댓글을 달려면 로그인하십시오.




Community Treasure Hunt

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

Start Hunting!

Translated by