Combine time related columns into timestamp for data in csv
4 次查看(过去 30 天)
显示 更早的评论
Hi, I have a number of csv files where I would like change the way date and time data are recorded so that it is timestamped.
Time and data are currently stored as below:
year,month,day,hour,minute,second,data1,data2,data3
2009,1,1,0,0,0,2.9,12.1,7.1
I would like the CSV to read:
2009-01-01 00:00:00, 2.9, 12.1,7.1
I have tried the following script, which I appreciate has a few inefficiencies:
for y = 1:5
yStr = num2str(y);
C = csvread([folderPath,'c',yStr,'.csv']);
t = string(datestr(datetime(C(:,1),C(:,2),C(:,3),C(:,4),C(:,5),C(:,6)), 'yyyy-mm-dd HH:MM:SS'));
D = [t,C(:,7),C(:,8),C(:,9)];
csvfilename = 'd'+string(y)+'.csv';
csvwrite(csvfilename,D);
end
However the output I get has each individual letter in the string seperated by a comma.
How do I get the script to record the timestamp in my preferred format? The data stored in the variable 't' looks correct when viewed
0 个评论
采纳的回答
Dave B
2021-9-7
编辑:Dave B
2021-9-7
The datestr is perhaps adding confusion?
This page has some good information on how to format datetimes: https://www.mathworks.com/help/matlab/matlab_prog/set-display-format-of-date-and-time-arrays.html
%% Generate some data that looks like your C
somerandomdates = datetime('now') - days(rand(100,1)*10);
C = [somerandomdates.Year somerandomdates.Month somerandomdates.Day somerandomdates.Hour somerandomdates.Minute somerandomdates.Second];
%% convert back to datetime, set the format, convert to string
dt = datetime(C); % Or you could use C(:,1:6) if you have more columns in your matrix
dt.Format = 'yyyy-MM-dd hh:mm:ss'; % note that MM is month, mm is minute
string(dt)
I'd also recommend considering writematrix instead of csvwrite, or you might consider writecell/writetable for your heterogenous data. If you load the data with readtable then writetable will work particularly well.
writematrix([string(dt) string(rand(size(dt)))], 'foo.csv')
3 个评论
Dave B
2021-9-7
No worries, if you have writematrix then by all means use it instead of csvwrite, it's better in every way. It sounds like this resolves your issue, but if you're still struggling or need to use csvwrite for some reason please let me know.
If you can use readtable/writetable instead, you may find it's even easier - tables work naturally with different types of variables, so you don't have to pretend that the values are all strings.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!