How can I convert a character vector that includes date time and random text to datetime format?
11 views (last 30 days)
Show older comments
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 Comment
Guillaume
on 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?
Accepted Answer
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
More Answers (2)
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')
0 Comments
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
0 Comments
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!