Merge datetime cells to create specific datetime format

조회 수: 2 (최근 30일)
Renan Deuter
Renan Deuter 2021년 2월 22일
답변: Jeremy Hughes 2021년 2월 22일
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