Why can't I convert from datenum to datetime?

3 ビュー (過去 30 日間)
Louise Wilson
Louise Wilson 2020 年 4 月 27 日
コメント済み: Louise Wilson 2020 年 4 月 28 日
I am trying to convert a vector of datenums to datetime but for some reason having issues. The spreadsheet I am working with is 7gb so I will just include the top rows.
%Data (d) example:
7.3782e+05 79.064 80.016 75.023
7.3782e+05 79.137 80.478 75.399
7.3782e+05 78.144 79.663 75.5
d_times=d(:,1);
d_times=datetime(d_times, 'ConvertFrom', 'datenum'); %convert t column datenums to date and time
When I do this I get the error:
Error using datetime (line 658)
Input data must be a numeric array, a string array, a cell array containing character vectors, or a char matrix.
...but I can see that the first value is a datetime? Where am I going wrong?

採用された回答

Stephen23
Stephen23 2020 年 4 月 27 日
You imported that data into a table (e.g. using readtable) and so you are using the wrong indexing:
You would need to use curly braces to get the numeric data out of the table:
d_times = d{:,1};
% ^ ^ you need these
Even better would be to use the variable name (which you have not told us):
d_times = d.nameofthefirstcolumn;
  1 件のコメント
Louise Wilson
Louise Wilson 2020 年 4 月 28 日
Thanks Stephen. I didn't include variable names in my table-the first row of the first column was 0. I managed to get around this problem by importing the data using csvread instead. Following this, everything works fine. Since I only needed to do this to check the datetimes were correct following subsetting the data, I will leave it I think. But, this is really good to know! I didn't realise the indexing was wrong. Thank you.

サインインしてコメントする。

その他の回答 (1 件)

per isakson
per isakson 2020 年 4 月 27 日
編集済み: per isakson 2020 年 4 月 27 日
The datetime statement is ok.
>> d_times=datetime( now, 'ConvertFrom', 'datenum');
>> d_times
d_times =
datetime
27-Apr-2020 05:27:05
>>
This script
%%
d = [
7.3782e+05 79.064 80.016 75.023
7.3782e+05 79.137 80.478 75.399
7.3782e+05 78.144 79.663 75.5
];
d1 = d(:,1);
%%
d_times = datetime( d1, 'ConvertFrom', 'datenum')
returns
d_times =
3×1 datetime array
30-Jan-2020 00:00:00
30-Jan-2020 00:00:00
30-Jan-2020 00:00:00
>>
I guess there is some kind of problem with your value of d(:,1)
Proposal: Replace
d_times=d(:,1);
by
d1 = d(:,1);
run the script and inspect the value of d1
Try
d1 = d( 1:end-2, 1 );

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by