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

4 ビュー (過去 30 日間)
Steve Ward
Steve Ward 2015 年 2 月 2 日
回答済み: Peter Perkins 2015 年 2 月 3 日
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 Center および File ExchangeDates and Time についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by