필터 지우기
필터 지우기

How can I read a csv file into datetime values, where the dates are formatted differently between different rows?

조회 수: 14 (최근 30일)
I have a .csv file with the first column containing dates, a snippet of which looks like the following:
date,values
03/11/2020,1
03/12/2020,2
3/14/20,3
3/15/20,4
3/16/20,5
04/01/2020,6
I would like to import this data into Matlab (I think the best way would probably be using the readtable() function. My goal is to bring the dates into Matlab as a datetime array. As you can see above, the problem is that the dates in the original .csv file are not consistently formatted. Some of them are in the format mm/dd/yyyy and some of them are mm/dd/yy.
Simply calling data = readtable('myfile.csv') on the .csv file results in the following, which is not quite correct:
'03/11/2020' 1
'03/12/2020' 2
'03/14/0020' 3
'03/15/0020' 4
'03/16/0020' 5
'04/01/2020' 6
Does anyone know a way to automatically account for this type of data in the import?
Thank you!

채택된 답변

Ankriti Sachan
Ankriti Sachan 2020년 5월 13일
You should try preprocessing your table data before reading it completely. readdata() function automatically detects the datatype of the column.
As a workaround, try to read the first column of your data as text using ‘textscan’ function (https://www.mathworks.com/help/matlab/ref/textscan.html) as text and change it to one common datetime format and then read this modified data completely using readtable() function. You can, however, read the complete data using ‘textscan’ function itself and use it.
  댓글 수: 1
Walter Roberson
Walter Roberson 2020년 5월 13일
If you use textscan with '%{dd/MM/yy}D' format, then it will automatically handle 2 digit years as being previous century for up to 50 years in the past, and current century for up to 50 years in the future; and it will handle 4 digit years fine.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by