【问题标题】:converting yyyy-mm-dd hh:mm:ss.ms to yyyy-mm-dd hh:mm:ss using matlab使用 matlab 将 yyyy-mm-dd hh:mm:ss.ms 转换为 yyyy-mm-dd hh:mm:ss
【发布时间】:2017-05-18 23:52:09
【问题描述】:
我收到了格式为yyyy-mm-dd HH:MM:SS.ms 的时间戳数据集。我想转换成yyyy-mm-dd HH:MM:SS 格式。有没有办法使用matlab只选择这种格式?
例如:
2012-08-01 00:10:00.0
应该是:
2012-08-01 00:10:00
请注意毫秒值全为零。
【问题讨论】:
标签:
arrays
matlab
date
datetime
time-series
【解决方案1】:
一般的方法是使用datestr 将其转换为您想要的格式。
dates = {'2012-08-01 00:10:00.1';
'2012-08-01 00:10:00.1'};
new = datestr(dates, 'yyyy-mm-dd HH:MM:SS');
% 2012-08-01 00:10:00
% 2012-08-01 00:10:00
另一种方法是,由于您的所有毫秒都将为零(因此您不必担心舍入),您可以使用正则表达式删除毫秒部分(小数点后的任何内容)
new = regexprep(dates, '\..*', '')
这可能会更高效,因为您不需要执行转换为 datetime 对象或日期编号的中间步骤。
【解决方案2】:
由于输入和输出格式除了毫秒之外都一样,所以不要使用日期函数,而是简单的字符串操作:
% example dates
C = {'2012-08-01 00:10:00.0'
'2013-08-02 00:11:11.0'
'2014-08-03 00:12:22.0'
'2015-08-04 00:13:33.0'
'2016-08-05 00:14:44.0'};
% method 1
D = cellfun(@(x)x(1:end-2), C, 'UniformOutput', false);
% method 2 (same, but no cellfun)
D = char(C);
D = cellstr(D(:,1:end-2));
% method 3
D = regexp(C, '[^\.]*', 'match', 'once');
% method 4
D = regexprep(C, '\..*$', '');
【解决方案3】:
假设您无论如何都需要这些数据在日期时间对象中,那么我会做这样的事情:
inp = {'2012-08-01 00:10:00.0'; '2012-08-02 04:10:00.0'}; % Some datestrins
t = datetime(inp,'InputFormat','yyyy-MM-dd HH:mm:ss.0'); % Convert to datetimes
datestr(t, 'yyyy-mm-dd HH:MM:SS') % convert back to strings
对于input & output 格式化程序,请参阅文档。我假设最后一部分总是零。