Merge datetime cells to create specific datetime format

2 次查看(过去 30 天)
Hi,
I used textscan to import an .txt file.
file = textscan(fileID,'%{yyyy}D %{MM}D %{dd}D %{HH}D %{mm}D %f %f %f %f','Delimiter',',', 'headerLines', 1)
Now I have 9 different cells. Cell 1 contains yyyy (2018), cell 2 contains MM (05) and Cell 3 DD (22).
However I want to merge YMD to one cell with the %{ddMMyy}D format. How can I do that? Output format should then be: 22052018
Thank you in Advance,
Renan

采纳的回答

Renan Deuter
Renan Deuter 2021-2-22
Hello,
so I found the solution by myself and will share it to later users having an similar issue:
The way to go is formatting the data from datetime -> string then merge it and then back to datetime again.
Useful functions are datestr and strcat
In my case this can be done by:
% create grabber_date
% loading the variables into length x 1 datetimes
year = grabber_file{1,1};
month = grabber_file{1,2};
day = grabber_file{1,3};
% convert to string
y = datestr(year, 'yy');
m = datestr(month, 'mm');
d = datestr(day, 'dd');
% merge using strcat
datestring = strcat(d, m, y);
% transform back to datetime
grabber_date = datetime(datestring,'InputFormat','ddMMyy', 'Format','ddMMyy');
The Output format can be varied by changing 'Format'.
You can also convert integers/doubles to datetime by using this tunnel. Just use num2str instead of datestr.
Best Regards,
Renan

更多回答(1 个)

Jeremy Hughes
Jeremy Hughes 2021-2-22
If your data looks like:
2021,02,22,02,30,...
then you might be better off calling readmatrix, and converting the columns
A = readmatrix(file)
T = datetime([A(:,1:5),zeros(height(A),1)])

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by