Converting table data to datetime
81 次查看(过去 30 天)
显示 更早的评论
I have data in a .csv file. The second column contains time data. I want to convert it to datetime.
My code is:
tbldata=readtable('pipe2_st.csv');
tbldataarray=table2cell(tbldata);
data1 = tbldataarray (:,2);
t = datetime(data1,'InputFormat', '[HH:mm:ss.SSS]');
The data in 'data1' is:
{[01:05:17.319]}
{[01:05:17.328]}
{[01:05:17.338]}
{[01:05:17.347]}
{[01:05:17.357]}
{[01:05:17.365]}
{[01:05:17.385]}
{[01:05:17.394]}
{[01:05:17.403]}
{[01:05:17.412]}
{[01:05:17.422]}
{[01:05:17.432]}
{[01:05:17.441]}
{[01:05:17.450]}
{[01:05:17.460]}
{[01:05:17.469]}
{[01:05:17.478]}
{[01:05:17.488]}
{[01:05:17.497]}
{[01:05:17.506]}
{[01:05:17.516]}
{[01:05:17.525]}
{[01:05:17.534]}
{[01:05:17.544]}
It gives the error:
Error using datetime (line 672)
Input data must be a numeric array, a string array, a cell array containing character vectors, or a char matrix.
Kindly help in resolving the error.
采纳的回答
Cris LaPierre
2023-4-12
编辑:Cris LaPierre
2023-4-12
You need a date to make it a datetime (it will automatically use today if you don't supply one). Perhaps you want to use duration instead?
readtable should automatically read in the data as a duration, which has all the same benefits when it comes to tima as a datetime. There is no need to use table2cell. Instead, see how to access data in tables.
Coverting what you show as output to a csv file (attached), here is what my code would be.
tbldata=readtable('pipe2_st.csv')
% Extract the Var1 variable from the table
tbldata.Var1
更多回答(1 个)
dpb
2023-4-12
编辑:dpb
2023-4-12
tbldata=readtable('pipe2_st.csv');
tbldataarray=table2cell(tbldata);
Don't convert the table to a cell array, use the table you've already got.....the form of the data output (a time string inside the square brackets all inside the curly braces) indicates readtable read the column as a duration variable already; you don't need to do anything with it other than perhaps combine it with the date ithat one presumes is in the first column.
I put the first few lines of your data above into a file with the above assumption...
>> tT=readtable('test.csv');
>> head(tT)
ans =
8×1 table
Var1
____________
01:05:17.319
01:05:17.328
01:05:17.338
01:05:17.347
01:05:17.357
01:05:17.365
01:05:17.385
01:05:17.394
>>
Then did the nasty thing of turning a perfectly good table into a cell array...
>> table2cell(ans)
ans =
8×1 cell array
{[01:05:17.319]}
{[01:05:17.328]}
{[01:05:17.338]}
{[01:05:17.347]}
{[01:05:17.357]}
{[01:05:17.365]}
{[01:05:17.385]}
{[01:05:17.394]}
>>
That's where the artifacts of the {[...]} came from, you just didn't look at the content of the table variables themselves...
>> isduration(tT.Var1)
ans =
logical
1
>> 1
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!