How to convert a datenum to a datetime?

Hi, I have table with column of datenum. I need to do a join with another table which has also a column of date but in just a plain format such as '11/1/2017'. But I got this error: Left and right key variables 'Date' and 'Date' are not comparable because one is a non-cell. How to resolve this error? Thanks a lot!

 採用された回答

Star Strider
Star Strider 2017 年 11 月 17 日

13 投票

Use the 'ConvertFrom' option:
t = datetime(X,'ConvertFrom','datenum')

6 件のコメント

JFz
JFz 2017 年 11 月 17 日
Thanks. This line works. But the join is still not working, because the table A.Date is array of cells; table B.Date is array of datetime. How to make them to be either both datetime or cell?
Star Strider
Star Strider 2017 年 11 月 17 日
Something like this will work:
dt = datetime([now+(0:6)], 'ConvertFrom','datenum')'; % ‘datetime’ Array
dtc = mat2cell(dt, ones(size(dt,1),1), 1); % ‘cell’ Array
dtt = cell2table(dtc); % ‘table’ Array
Change it appropriately to work with your code.
JFz
JFz 2017 年 11 月 17 日
Thank you! let me try it....
JFz
JFz 2017 年 11 月 17 日
It will take sometime to find out since it is inside a large application.
JFz
JFz 2017 年 11 月 17 日
Works. Thanks!
Star Strider
Star Strider 2017 年 11 月 17 日
My pleasure!

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

その他の回答 (1 件)

Peter Perkins
Peter Perkins 2017 年 11 月 20 日

1 投票

Star Strider's answer seems like the long way around. JFz, it always helps to provide a short concrete example so people don't have to guess, but it sounds like you have one table with a datenum variable and another with a datestr variable,
>> t1 = table(floor(now) + [1;2;3],[1;2;3],'VariableNames',{'Date' 'X'})
t1 =
3×2 table
Date X
______ _
737020 1
737021 2
737022 3
>> t2 = table(datestr(floor(now) + [3;2;1]),[33;22;11],'VariableNames',{'Date' 'Y'})
t2 =
3×2 table
Date Y
___________ __
[1x11 char] 33
[1x11 char] 22
[1x11 char] 11
and you want to join the two tables using dates as the key. Convert the dates to datetimes, and you're done:
>> t1.Date = datetime(t1.Date,'ConvertFrom','datenum')
t1 =
3×2 table
Date X
____________________ _
21-Nov-2017 00:00:00 1
22-Nov-2017 00:00:00 2
23-Nov-2017 00:00:00 3
>> t2.Date = datetime(t2.Date)
t2 =
3×2 table
Date Y
___________ __
23-Nov-2017 33
22-Nov-2017 22
21-Nov-2017 11
>> t3 = join(t1,t2)
t3 =
3×3 table
Date X Y
____________________ _ __
21-Nov-2017 00:00:00 1 11
22-Nov-2017 00:00:00 2 22
23-Nov-2017 00:00:00 3 33

1 件のコメント

JFz
JFz 2017 年 11 月 20 日
Yes! You are giving an excellent example. Thank you!

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

カテゴリ

ヘルプ センター および File ExchangeDates and Time についてさらに検索

製品

タグ

質問済み:

JFz
2017 年 11 月 17 日

コメント済み:

JFz
2017 年 11 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by