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

5 vues (au cours des 30 derniers jours)
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

Réponses (3)

David Young
David Young le 2 Fév 2015
Modifié(e) : David Young le 2 Fév 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 le 2 Fév 2015
Modifié(e) : Guillaume le 2 Fév 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 le 3 Fév 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'

Catégories

En savoir plus sur Dates and Time dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by