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
0 个评论
回答(3 个)
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.]
0 个评论
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)]
0 个评论
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'
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Dates and Time 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!