How to use 'setvartype' to get the variable as 'datetime' formatted as: yyyy-MM-dd
20 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Pawel Jastrzebski
am 25 Jul. 2018
Kommentiert: Pawel Jastrzebski
am 6 Aug. 2018
I've got a spreadsheet which gets imported into Matlab via readtable().
Prior to importing I use detectImportOptions() and setvartype() to change the type of certain variables.
Everything works well but one thing, I want the date column of my data to be imported as 'yyyy-MM-dd', but by default I get it gives me 'dd-MM-yyy-hh-mm-ss'.
Problem: I want to ditch the hour-minute-second bit of the date as I don't need it. How to do it via detectImportOptions?
My code:
FileName = 'AllTestData.xlsx';
% detect 'READTABLE' import options for the given sheet
opts = detectImportOptions(FileName);
opts = setvartype(opts,{'Test_Date',},'datetime');
% Import data:
tAllTestData = readtable(FileName,opts);
My current workaround is that, I add this line at the end of code:
tAllTestData.Test_Date = datetime(tAllTestData1.Test_Date,'format', 'yyyy-MM-dd');
But like I said, I'd like to get all the import settings adjusted prior to importing.
To illustrate my problem:
0 Kommentare
Akzeptierte Antwort
Harsh
am 25 Jul. 2018
For example:
>> datetime.setDefaultFormats('default','yyyy-MM-dd');
>> FileName = 'AllTestData.xlsx';
>> opts = detectImportOptions(FileName);
>> opts = setvartype(opts,{'Test_Date'},'datetime');
>> tAllTestData = readtable(FileName,opts);
>> head(tAllTestData)
ans =
8×2 table
Nr Test_Date
__ __________
1 2017-08-24
2 2017-08-29
3 2017-08-31
4 2017-09-01
5 2017-09-04
6 2017-09-05
7 2017-12-07
8 2017-12-12
3 Kommentare
Harsh
am 25 Jul. 2018
Just to add, alternatively, you could also do the following:
..
>> opts = setvartype(opts,{'Test_Date'},'datetime');
>> opts = setvaropts(opts,{'Test_Date'},'InputFormat','yyyy-MM-dd');
..
Weitere Antworten (1)
Peter Perkins
am 3 Aug. 2018
Pawel, if I understand your question correctly, this is just a display issue. The datetime in the middle and right images are the same value, it's just the the right-hand one doesn't display HH:mm:ss. One simple thing to do is set the format after importing:
tallTestData.TestDate.Format = 'dd-MMM-yyyy'
Maybe that's what you've already done, and you wanted to do it as part of the import. But just to be clear: all that is is a display format.
Siehe auch
Kategorien
Mehr zu Whos finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!