Borrar filtros
Borrar filtros

How can I convert a character vector that includes date time and random text to datetime format?

5 visualizaciones (últimos 30 días)
I will like to convert a character vector which contains info like this '2018-05-19_07.11.16_test6.csv' to datetime format. The info I actually need is the date (2018-05-19) and time (07.11.16). How can I do this? Thank you!
  1 comentario
Guillaume
Guillaume el 16 de Nov. de 2018
Is the date and time format consistent?
Is the location of the random text consistent?
If so, what is the actual pattern?

Iniciar sesión para comentar.

Respuesta aceptada

the cyclist
the cyclist el 16 de Nov. de 2018
Guessing at the pattern ...
s = '2018-05-19_07.11.16_test6.csv'
idx = regexp(s,'_')
d = s(1:idx(1)-1)
t = s(idx(1)+1:idx(2)-1)
  3 comentarios
Stephen23
Stephen23 el 16 de Nov. de 2018
Editada: Stephen23 el 16 de Nov. de 2018
Simpler to use the 'split' option::
>> S = '2018-05-19_07.11.16_test6.csv';
>> C = regexp(S,'_','split');
>> d = C{1}
d = 2018-05-19
>> t = C{2}
t = 07.11.16

Iniciar sesión para comentar.

Más respuestas (2)

Adam Danz
Adam Danz el 16 de Nov. de 2018
This fits the pattern in your example but it is not robust to pattern changes.
t = '2018-05-19_07.11.16_test6.csv';
dtchar = regexp(t, '\d+-\d+-\d+_\d+.\d+.\d+', 'match'); %date-time characters
dt = datetime(dtchar, 'InputFormat', 'yyyy-MM-dd_HH.mm.ss')

Peter Perkins
Peter Perkins el 19 de Nov. de 2018
None of this will work unles the format is stable, and if it is, a simpler version would be
>> t = '2018-05-19_07.11.16_test6.csv';
>> dt = datetime(t(1:19), 'InputFormat', 'yyyy-MM-dd_HH.mm.ss')
dt =
datetime
19-May-2018 07:11:16
If you are doing this for more than one file name, you presumably have those in a cell array of char row vectors, or (preferably) a string array. A simple modification
>> t = ["2018-05-19_07.11.16_test6.csv"; "2018-05-19_07.11.15_test77.csv"; "2018-05-19_07.11.18_test888.csv"];
>> dt = datetime(extractBefore(t,20), 'InputFormat', 'yyyy-MM-dd_HH.mm.ss')
dt =
3×1 datetime array
19-May-2018 07:11:16
19-May-2018 07:11:15
19-May-2018 07:11:18

Categorías

Más información sobre Logical 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