When export date/time to excel, change the time(mm:ss)..
Show older comments
Hi all.
I have a problem.
Now, time is 2017-02-05 21:35:32.
But I want to export 2017-02-05 21:00:00 except minute, scecond.
But when I use writetable(to .xlsx), time changed 2017-02-05 21:35:32 in excel.
t = datetime('now','TimeZone','Asia/Seoul','Format','yyyy-MM-dd HH:00:00') % 2017-02-05 21:00:00
T = table(t); % 2017-02-05 21:00:00
writetable(T,filename); % 2017-02-05 21:35:32
What is problem in this code?
Accepted Answer
More Answers (1)
What's wrong is the confusing nature of what the 'Format' property actually does with datetime variables; it only affects the output display of the time value, NOT the value of the time stored...example--
>> T=table(datetime('now','TimeZone','Asia/Seoul','Format','yyyy-MM-dd HH:00:00'));
>> t=T.Var1 % looks like an even hour, doesn't it?
t =
2017-02-05 23:00:00
>> whos t % is a datetime object, too...
Name Size Bytes Class Attributes
t 1x1 123 datetime
>> t.Format % the format is as noted to hours only
ans =
yyyy-MM-dd HH:00:00
>> t.Format='default' % now change that property
t =
05-Feb-2017 23:39:46
>>
and Voila! -- the actual time stored is revealed; the Format property hid what was really there.
You'll have to convert the time values you have to either datenum or datetime values by converting to the actual time values wanted. One way (not sure it's necessarily the most efficient) is to convert the output string with the desired format back to numeric internal form to get those values to be output.
Example--
>>t=datetime('now','Format','yyyy-MM-dd HH:00:00'); % a current time value
>> t.Format='default' % what is actual? (Does have MM:ss as expect)
t =
05-Feb-2017 09:02:48
>> t.Format='yyyy-MM-dd HH:00:00'; % set format to remove MM:ss
>> datetime(char(t)) % convert that string back to datetime
ans =
05-Feb-2017 09:00:00
>>
NB: Final result in default format show 00:00 for MM:ss; successfully rounded to hours only as desired.
>> t
t =
2017-02-05 09:00:00
>>
2 Comments
Robert
on 12 Oct 2022
The question was to not export minutes and seconds.
Your answer exports 2017-02-05 09:00:00 while the question asks for 2017-02-05 09
How can that be achieved?
dpb
on 12 Oct 2022
As the note/text says, it was an example for the OP to mung upon as chose/needed/wanted to match need illustrating the way to get whatever format is wanted.
Categories
Find more on Dates and Time 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!