How do I convert this string to a date ?
조회 수: 57 (최근 30일)
이전 댓글 표시
Hi everybody !
I'm trying to turn this string to a date (from a txt file): 2021-05-11T14:11:00Z to 'yyyy-MM-dd HH:mm:ss'.
I tried with datetime(ref_time(h, 1),'InputFormat', 'yyyy-MM-dd e HH:mm:ss e','Format','yyyy-MM-dd HH:mm:ss') with an 'e' replacing the 'T' and 'Z' but id doesn't work...
댓글 수: 0
답변 (2개)
Asmit Singh
2021년 5월 26일
Since you are trying to convert strings to date with literals like 'T' and 'Z', you may want to look at the "Date and Time from Text with Literal Characters" section in the documentation.
The below code converts the given string format to matlab datetime variable.
myDate = "2021-05-11T14:11:10Z"
datetime(myDate,'InputFormat','yyyy-MM-dd''T''HH:mm:ss''Z')
댓글 수: 8
Stephen23
2021년 6월 1일
편집: Stephen23
2021년 6월 1일
@Jules PASCO: Of course it will not work: does the "InputFormat" match the input data format? (hint: no)
This is what you are telling MATLAB (and us in your question) that your dates looks like:
'yyyy-MM-dd e HH:mm:ss e'
whereas this is (apparently) what your dates actually look like:
'04-May-2021 11:00:00'
Are they the same format? (hint: no)
"The only problem is that I can't turn this format into a datetime, it stays a string."
It works for me:
S = '04-May-2021 11:00:00';
T = datetime(S, 'InputFormat','dd-MMM-yyyy HH:mm:ss') % !!! DATETIME !!!
T.Format = 'yyyy-MM-dd HH:mm:ss' % !!! Still DATETIME !!!
Did you specify the InputFormat to actually match the data you have?
Allen
2021년 5월 26일
Try running a string replacement to remove "T" and "Z" from your string before reformatting to datetime.
str = "2021-05-11T14:11:00Z";
datetime(regexprep(str,["T","Z"],[" ",""]))
댓글 수: 1
Stephen23
2021년 5월 26일
The "T" is specified in ISO 8601, it would be a very unfortunate if DATETIME could not handle it:
The "Z" refers to the Zulu time zone:
and as such it conveys important information which cannot be disregarded:
S = '2021-05-11T14:11:00Z';
T = datetime(S,'InputFormat','yyyy-MM-dd''T''HH:mm:ssZ', 'TimeZone','UTC')
T.TimeZone = 'Asia/Shanghai'
참고 항목
카테고리
Help Center 및 File Exchange에서 Categorical Arrays에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!