Filter löschen
Filter löschen

Merge datetime cells to create specific datetime format

3 Ansichten (letzte 30 Tage)
Renan Deuter
Renan Deuter am 22 Feb. 2021
Beantwortet: Jeremy Hughes am 22 Feb. 2021
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

Akzeptierte Antwort

Renan Deuter
Renan Deuter am 22 Feb. 2021
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

Weitere Antworten (1)

Jeremy Hughes
Jeremy Hughes am 22 Feb. 2021
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)])

Kategorien

Mehr zu Dates and Time finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by