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

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

Answers (3)

David Young
David Young on 2 Feb 2015
Edited: David Young on 2 Feb 2015
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 on 2 Feb 2015
Edited: Guillaume on 2 Feb 2015
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 on 3 Feb 2015
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'

Categories

Find more on Dates and Time in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!