Merge datetime cells to create specific datetime format

2 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Renan Deuter
Renan Deuter el 22 de Feb. de 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

Más respuestas (1)

Jeremy Hughes
Jeremy Hughes el 22 de Feb. de 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)])

Categorías

Más información sobre Dates and Time en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by