How do split columns of dates in the format 'dd mm yyyy hh:mm:ss' to get just hh:mm?

조회 수: 5 (최근 30일)
I have a variable containing a column vector of dates in the format 'dd mm yyyy hh:mm:ss' and want to create another column vector next to it or variable in the format hh:mm

답변 (3개)

David Young
David Young 2015년 2월 2일
편집: David Young 2015년 2월 2일
I assume from the formats that your variable is a cell vector of strings, and that you want the result to also be a cell vector of strings.
% test data
datestrings = {'20 07 1872 13:22:16'; '01 03 2020 05:42:06'; '28 02 1999 12:00:00'};
% column vector with times only in format HH:MM
timestrings = cellstr(datestr(datenum(datestrings, 'dd mm yyyy HH:MM:SS'), 'HH:MM'))
[Edit: added call to cellstr after seeing Guillaume's answer.]

Guillaume
Guillaume 2015년 2월 2일
편집: Guillaume 2015년 2월 2일
Option 1: Convert to datenum (or datevec or the new datetime) and back to string:
myvar = {'31 01 2015 15:24:59'; '02 02 2013 01:02:03'};
dnmyvar = datenum(myvar, 'dd mm yyyy HH:MM:SS');
mynewvar = [myvar num2cell(datestr(dnmyvar, 'HH:MM'), 2)]
Option 2: use regexp:
myvar = {'31 01 2015 15:24:59'; '02 02 2013 01:02:03'};
mynewvar = [myvar regexp(myvar, '\d\d:\d\d', 'match', 'once')] %regexp could be more robust if wanted
Option 3: hardcode the range to extract (not as good):
myvar = {'31 01 2015 15:24:59'; '02 02 2013 01:02:03'};
mynewvar = [myvar cellfun(@(d) d(12:16), myvar, 'UniformOutput', false)]

Peter Perkins
Peter Perkins 2015년 2월 3일
If you have access to R2014b, try this:
>> datestrings = {'20 07 1872 13:22:16'; '01 03 2020 05:42:06'; '28 02 1999 12:00:00'}
datestrings =
'20 07 1872 13:22:16'
'01 03 2020 05:42:06'
'28 02 1999 12:00:00'
>> dt = datetime(datestrings,'Format','dd MM yyyy HH:mm:ss')
dt =
20 07 1872 13:22:16
01 03 2020 05:42:06
28 02 1999 12:00:00
>> t = timeofday(dt)
t =
13:22:16
05:42:06
12:00:00
>> tstr = cellstr(t,'hh:mm')
tstr =
'13:22'
'05:42'
'12:00'

카테고리

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