Borrar filtros
Borrar filtros

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

12 visualizaciones (últimos 30 días)
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!

Respuesta aceptada

Ankriti Sachan
Ankriti Sachan el 13 de Mayo de 2020
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 comentario
Walter Roberson
Walter Roberson el 13 de Mayo de 2020
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.

Iniciar sesión para comentar.

Más respuestas (0)

Productos


Versión

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by