readtable with datetime, format problem

조회 수: 61 (최근 30일)
dormant
dormant 2023년 10월 17일
답변: Steven Lord 2023년 10월 17일
I continue to struggle with datetime, having spent years using datenum.
I'm using readtable to read in a .csv file that has been created in Excel. One of the columns is date and time, in dd/MM/yyyy hh:mm format. MATLAB seems to assume it is in MM/dd/yyy format, ie:
>> X = readtable( fileWeather );
>> X.DateTime(1)
ans =
datetime
12/10/2023 00:00
>> datestr(X.DateTime(1))
ans =
'10-Dec-2023'
How do I properly read the date in the dd/MM/yyyy format?
I've tried setting the default like below, but it seems to have no effect.
datetime.setDefaultFormats('defaultdate','dd/MM/yyyy')

채택된 답변

Star Strider
Star Strider 2023년 10월 17일
편집: Star Strider 2023년 10월 17일
How do I properly read the date in the dd/MM/yyyy format?
You need to tell datetime:
DateTime = datetime('12/10/2023 00:00', 'InputFormat','dd/MM/yyyy HH:mm')
DateTime = datetime
12-Oct-2023
optionally:
DateTime = datetime('12/10/2023 00:00', 'InputFormat','dd/MM/yyyy HH:mm', 'Format','dd/MM/yyyy HH:mm')
DateTime = datetime
12/10/2023 00:00
EDIT — Added the second datetime call, uising the 'Format' name-value pair to format the output.
.

추가 답변 (1개)

Steven Lord
Steven Lord 2023년 10월 17일
Try calling detectImportOptions on the file to let MATLAB try to figure out the format of the file. Check how it thinks the date and time data should be imported. If the format is not correct, use the setvaropts function to change the InputFormat option for the variable into which your date and time data will be imported. Finally pass the struct created by detectImportOptions (and perhaps modified by setvaropts) into readtable.
Or if you have multiple files in the same format to import, consider configuring how you want MATLAB to import the data using the Import Tool then generate a script or function to import the data (click the small down arrow on the Import Selection button then select one of the "Generate" options.) This lets you experiment and iterate on reading in your data.

카테고리

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

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by