How to extract date time from format unique to InputFormat?
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Muha
el 12 de Nov. de 2024
Comentada: Cris LaPierre
el 21 de Nov. de 2024 a las 21:46
I have data set extracted in the form ´05/17/24 04p:48:15.8148625´. These data sets are not fond in the InputFormat list, contains a 'p' for postmeridian, and has seconds up to 7 decimal places. I am ok if it is inevitable to round-off the seconds, however, I will be working with several formats and the manual way of extracting parts of strings, joining them together in InputFormat list is quite hectic and it slows down my code. Is there a way we can simply use datetime command to convert the text into datetime? I will appreciate your help. Thanks.
load('data_imp.mat');
dttime = datetime(data_imp,"InputFormat","MM/dd/uu 'T'HH:mm:ss.SSSSSSS");
0 comentarios
Respuesta aceptada
Shashi Kiran
el 12 de Nov. de 2024
To convert your data into "datetime" format in MATLAB, you can use "regexprep" to handle the PM adjustment. Here’s how:
load('data_imp.mat')
% Adjust PM hours
data_adj = regexprep(string(data_imp), '(\d{2})p:', '${num2str(str2double($1) + 12, ''%02d'')}:');
% Convert to datetime
dttime = datetime(data_adj, 'InputFormat', 'MM/dd/yy HH:mm:ss.SSSSSSS')
For more details on "regexprep", refer to the documentation here: https://www.mathworks.com/help/matlab/ref/regexprep.html
Hope this helps!
Más respuestas (2)
Cris LaPierre
el 12 de Nov. de 2024
The format used to represent am/pm (04p:48:15.8148625) is not one recognized by MATLAB. You therefore need to manipulate your data into a format that MATLAB can recognize.
My approach would be
- capture which rows contain pm times
- remove the am/pm designation
- convert times to datetimes
- add 12 hours to rows containing pm times
load('data_imp.mat')
data_imp
% capture pm times
pmTms = cellfun(@(x) contains(x,'p:'),data_imp);
% remove am/pm designation
data_imp = replace(data_imp,lettersPattern + ':',':')
% convert to datetime
dttime = datetime(data_imp,"InputFormat","MM/dd/yy hh:mm:ss.SSSSSSS");
% add 12 hours to pm times
dttime(pmTms) = dttime + hours(12)
Peter Perkins
el 21 de Nov. de 2024 a las 21:44
Another possibility:
str = "05/17/24 04p:48:15.8148625"
str = replace(str,"p","pm")
datetime(str,InputFormat="MM/dd/yy hha:mm:ss.SSSSSSS")
1 comentario
Ver también
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!