将表字符串转换为日期编号



我有带有字符串的 Matlab 表,我想将其转换为 datenum 格式。我试过了:

datenum(Tbl) 

但我收到错误:

Error using datenum (line 181)
DATENUM failed.
Caused by:
Error using datevec (line 103)
The input to DATEVEC was not an array of character vectors.

这是我的 Tbl 示例:

Tbl = table;
Tbl.('A') = {'29/07/2017'; 0};
Tbl.('B') = {'29/07/2017'; '31/07/2017'};

试试varfun:

varfun(@datenum,Tbl)

生产

datenum_A    datenum_B
_________    _________
12791        12791    
0        13521    

选项 2

或者,可以像这样一次执行一列:

Tbl.('A') = cellfun(@datenum,Tbl.('A'))

生产

Tbl =

A           B      
_____    ____________
12791    '29/07/2017'
0    '31/07/2017'

然后你可以为"B"等做。

首先将表转换为数组,然后应用datenum日期格式。在数据中包含数字很奇怪,但无论如何,这里有一个解决方案:

numdate= table2array(Tbl);       %Converting table to array
ind = cellfun(@ischar,numdate);  %Finding logical indices of dates stored as char array
%Finding serial date number of dates; not doing anything on numeric values
numdate(ind)=cellfun(@(x) datenum(x, 'dd/mm/yyyy'), numdate(ind),'un',0); %Serial Datenums
%Converting back the date number serials into dates    
dateback=numdate; dateback(ind)=cellfun(@datestr,numdate(ind),'un',0); 

输出:

>> numdate
numdate =     
[736905]    [736905]
[     0]    [736907]
>> dateback
dateback =
'29-Jul-2017'    '29-Jul-2017'
[          0]    '31-Jul-2017'

最新更新