【问题标题】: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, '\..*$', '');
    

    【讨论】:

    • 感谢它很简单。你能帮我下面给出的相关问题链接吗stackoverflow.com/questions/41364396/… 虽然解决方案我得到了我的解决方案,但它非常冗长和复杂。你能告诉我用更简单的方法解决这个问题吗?
    【解决方案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 格式化程序,请参阅文档。我假设最后一部分总是零。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      相关资源
      最近更新 更多