Error in datetime array format for writing new matrix
Show older comments
Hello matlab expert, I have this timeseries data in txt format. the first column contain year data in year decimal format. I want to convert the year decimal format into datetime and save it as new txt file but I got an error in writematrix because the datetime format. what function should I use?
clc;clear; close all;
format long g
filename1 = 'C:\ZTD\PWVctul.txt';
data1 = readmatrix(filename1);
T1 = array2table(data1);
tt = table2timetable(T1, 'RowTimes',datetime(0,1,1) + years(data1(:,1)));
tt4 = timetable2table (tt);
pw = table2array (tt4(1:end,"data12"));
time = table2array (tt4(1:end,"Time"));
newdata = [ty pw];
writematrix (newdata,'PWVctuldatetime.txt','Delimiter','space');
4 Comments
dpb
on 14 Sep 2022
Put into a table and use writetable instead...
But, do you know the expected time to be returned for the given values?
> datetime(0,1,1)+years(2014.99980974125) % the first time value in the file
ans =
datetime
31-Dec-2014 13:37:56
>> 0.99980974125*365 % comparison conversion; 2014 is not leap year
ans =
364.9306
>> ans-364 % is Dec 31 but almost end of day
ans =
0.9306
>> ans*24
ans =
22.3333
>>
Seems to me the datetime conversion isn't correct hour, even though it gets day.
Futzing with starting point in datetime changes the day, but it always seems to return the same time...
@dpb: the approach shown is fundamentally flawed, because:
- it uses a fixed-length year of exactly 365.2425 days, see https://www.mathworks.com/help/matlab/ref/duration.years.html
- it does not take into account the (accumulated) different year lengths since year 0.
This is easy to illustrate with a very simple example which should be exactly midnight on Jan 1st, but is not:
datetime(0,1,1) + years(2022)
To get the correct year length for any specific year (required for that fraction), something like CALYEARS or DATESHIFT or two DATETIMES or similar would be required.
dpb
on 14 Sep 2022
I figured it had to be somesuch -- but didn't spend much time thinking about it nor about that years is the average duration animal...I was aware of that, just didn't think about it at the time.
Seems like a reasonable enhancement to the conversion types in datetime to build into it.
"Seems like a reasonable enhancement to the conversion types in datetime to build into it."
I asked about this on another thread, got this response:
Accepted Answer
More Answers (0)
Categories
Find more on Calendar 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!