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

조회 수: 11 (최근 30일)
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
Guillaume
Guillaume 2018년 11월 16일
Is the date and time format consistent?
Is the location of the random text consistent?
If so, what is the actual pattern?

댓글을 달려면 로그인하십시오.

채택된 답변

the cyclist
the cyclist 2018년 11월 16일
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
Stephen23
Stephen23 2018년 11월 16일
편집: Stephen23 2018년 11월 16일
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

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Adam Danz
Adam Danz 2018년 11월 16일
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 2018년 11월 19일
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

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by