How can I keep the same time format when exporting my Table to Excel?
26 views (last 30 days)
Show older comments
MathWorks Support Team
on 20 Jul 2018
Answered: MathWorks Support Team
on 9 Aug 2018
When I am trying to write time data from MATLAB to Excel, the time format is changing to a date and undesired time format. It is also based on the day I am writing the data to Excel.
For example, the time '03:05:12' in 'HH:mm:ss' format in a MATLAB table or array of cells becomes '07/18/2018 03:05:12 pm' in an Excel file cell if it's written to on '07/18/2018':
>> time = datetime(['03:05:12';'04:05:12';'05:05:12'],'Format','HH:mm:ss');
>> data = [1; 2; 3];
>> T = table(time,data);
>>
>> writetable(T, 'Book1.xlsx');
How to prevent it so that the time format 'HH:mm:ss' remains the same between MATLAB and Excel?
Accepted Answer
MathWorks Support Team
on 28 Sep 2018
The issue here is the use of "datetime" function to store time values. As the name of the function suggests, it takes both the date and time into account when it returns the output "time" in the question above. Since the input does not specify any date specifically, "datetime" function uses the current date as the date component of the output which explains why the data written to Excel is based on the day, the data is being written to Excel.
Since the input data corresponds to only time and not date, the correct function to use in this context is "duration" which represents elapsed times in units of fixed length, such as hours, minutes, and seconds. Using the "duration" function instead of "datetime" results in the data being written to Excel in the desired form:
>> time = duration({'03:05:12';'04:05:12';'05:05:12'},'Format','hh:mm:ss');
>> data = [1; 2; 3];
>> T = table(time,data);
>>
>> writetable(T, 'Book1.xlsx');
Here is the documentation for "duration" for your reference:
0 Comments
More Answers (0)
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!