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

5 views (last 30 days)
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!

Accepted Answer

the cyclist
the cyclist on 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 Comments
Stephen23
Stephen23 on 16 Nov 2018
Edited: Stephen23 on 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

Sign in to comment.

More Answers (2)

Adam Danz
Adam Danz on 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 on 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

Community Treasure Hunt

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

Start Hunting!