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

11 Ansichten (letzte 30 Tage)
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 Kommentar
Guillaume
Guillaume am 16 Nov. 2018
Is the date and time format consistent?
Is the location of the random text consistent?
If so, what is the actual pattern?

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

the cyclist
the cyclist am 16 Nov. 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 Kommentare
Stephen23
Stephen23 am 16 Nov. 2018
Bearbeitet: Stephen23 am 16 Nov. 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Adam Danz
Adam Danz am 16 Nov. 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 am 19 Nov. 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

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