how to read a text file as datetime input?

Hi everyone,
I have a text file with tiem date format YYYY-MM-DD HH:MM:SS. I want to load it and convert it to datenum. Here is what i attempt so far. (data attached)
cd_ev=readmatrix('tt.txt'); % file attached
%Or
t = load('tt.txt','InputFormat','yyyy-mm-dd HH:mm:ss')
%or
rr=readtable('tt.txt', 'Format','yyyy_mm_dd/dd hh:mm:ss');
None of the above serve fro my purpsoe.

 채택된 답변

Walter Roberson
Walter Roberson 2022년 10월 14일
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/1156138/tt.txt';
t1 = readtable(filename, 'ReadVariableNames', false);
t1.Properties.VariableNames{1} = 'Date';
t1.Date.Format = 'yyyy_MM_dd/dd HH:mm:ss'; %MM for month, HH for 24 hour hour
%verify
t1.Date(1:5)
ans = 5×1 datetime array
2015_07_10/10 04:43:53 2015_07_18/18 02:57:26 2015_07_27/27 04:59:29 2015_07_27/27 22:15:44 2015_09_13/13 08:23:58
I am having trouble thinking of a good reason to repeat the day like you asked to.

댓글 수: 7

Andi
Andi 2022년 10월 14일
편집: Andi 2022년 10월 14일
oh, it just a typo, no need to repeat the day. :P
But, the key thing is when i convert this to data num for further processing, there is still an error.
clear all
clc
filename = 'tt.txt';
t1 = readtable(filename, 'ReadVariableNames', false);
t1.Properties.VariableNames{1} = 'Date';
t1.Date.Format = 'yyyy_MM_dd HH:mm:ss'; %MM for month, HH for 24 hour hour
aa=t1.Date;
cand_ev=datenum(aa);
for jj=1:10
b=cand_ev(:,jj);
aa(jj)= addtodate(b, 3, 'day');
bb(jj)= addtodate(b, -3, 'day');
end
CE_U=aa;
CE_L=bb;
Error:
Error using addtodate
Date number must be a real numeric scalar.
Why do you need datenum? You can
aa = t1.Date + days(3);
bb = t1.Date - days(3);
Andi
Andi 2022년 10월 14일
편집: Andi 2022년 10월 14일
yes, i want to add and subtract 3 days from this time value. But it shoudl be in datenum because other datasets i am using in my code are in datenum
Consider converting the dates in the other databases to datetime(), using datetime() with 'convertfrom', 'datenum'
aa = datenum(t1.Date + days(3));
bb = datenum(t1.Date - days(3));
Andi
Andi 2022년 10월 14일
yes, i did but i dont known why datenum values are not competable with other datasets.
addtodate is specifically designed to only accept scalar datenum. b=cand_ev(:,jj); selected a vector of datenum entries, so addtodate(b) failed.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Time Series Objects에 대해 자세히 알아보기

제품

태그

질문:

2022년 10월 14일

댓글:

2022년 10월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by