How to use 'setvartype' to get the variable as 'datetime' formatted as: yyyy-MM-dd
20 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Harsh
2018-7-25
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 个评论
Harsh
2018-7-25
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');
..
更多回答(1 个)
Peter Perkins
2018-8-3
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!