【问题标题】:"Failed on converting date string to date number" due to mixed of timestamp format由于混合了时间戳格式,“将日期字符串转换为日期数字失败”
【发布时间】:2015-05-15 02:23:36
【问题描述】:

不知何故,我的原始数据的时间戳是,

A= 
{'12/5/2015 11:59:58 PM';
'13/5/2015'; % ideally this is '13/5/2015 12:00 AM'
'13/5/2015 12:00:01 AM;
'13/5/2015 12:00:01 AM}

由于时间戳格式混合,我无法执行 datenum,其中,

datenum(A,'dd/mm/yyyy HH:MM:SS PM') 给了我“将日期字符串转换为日期数字失败”

如何将 A 中的所有实体(具有 MIXED 时间格式)转换为时间数字序列?

【问题讨论】:

  • 感谢您的回复。我有一个具有不同时间格式的巨大样本集,需要“dd/mm/yyy HH:MM:SS PM”或“dd/mm/yyyy”格式。但是我不知道哪个索引需要哪种格式,如何将它们转换为一个整体的时间序列混合格式?

标签: string matlab date


【解决方案1】:

为了找到使用特定格式的索引,您可以使用正则表达式。
以较长的格式为例,并将其与您的 A 匹配:

longformat = '^\d\d/(1?)\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M$';
found = regexp(A,longformat) 
ans = 

    [1]
    []
    [1]
    [1]

因此,您可以使用匿名函数之类的方法来查找找到了哪些答案:

foundlong = @(A,expr) cellfun(@(x) ~isempty(x),regexp(A,expr));
found = foundlong(A,longformat)
found =

     1
     0
     1
     1

现在您有了索引,您可以在其中使用具有特定格式的datenum()。 例如:

d(found) = datenum(A{found},'dd/mm/yyyy HH:MM:SS AM');

注意:如果您以较短的表达式开头,请说

shortformat = '^\d\d/(1?)\d/\d\d\d\d'; 

您将匹配所有。因此,请确保在序列末尾添加 $,以匹配字符串的末尾:

shortformat = '^\d\d/(1?)\d/\d\d\d\d$'; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    相关资源
    最近更新 更多