I am trying to convert the date data from the CSV file to datetime, but it shows error, how do I fix this
조회 수: 5 (최근 30일)
이전 댓글 표시
dates=string(raw.textdata(2:end,1));%import the string dates from the data
dates=datetime(dates,'InputFormat','dd/MM/yy'); %convert date strings to date time format
%monthly vectors
m=unique(month(dates));%Get unique months form the data set
m_sum_Production=zeros(length(m),1);%initial monthly sum of Production
m_sum_T_Consumption=zeros(length(m),1);%initial monthly sum of Total Consumption
m_sum_O_Consumption=zeros(length(m),1);%initial monthly sum of Own Consumption
for i =1:length(m)
current_months=month(dates)==m(i); %checks each date to see if its month matches the current month
m_sum_Production(i) = sum(Production(current_months));%monthly sum of Production
m_sum_T_Consumption(i) = sum(T_Consumption(current_months));%monthly sum of Total Consumption
m_sum_O_Consumption(i) = sum(O_Consumption(current_months));%monthly sum of Own Consumption
end
code above
dates =
1505×1 string array
"06-Apr-20"
"07-Apr-20"
"08-Apr-20"
"09-Apr-20"
"10-Apr-20"
"11-Apr-20"
"12-Apr-20"
"13-Apr-20"
"14-Apr-20"
"15-Apr-20"
"16-Apr-20"
"17-Apr-20"
"18-Apr-20"
"19-Apr-20"
"20-Apr-20"
"21-Apr-20"
"22-Apr-20"
"23-Apr-20"
"24-Apr-20"
"25-Apr-20"
"26-Apr-20"
"27-Apr-20"
"28-Apr-20"
"29-Apr-20"
"30-Apr-20"
"01-May-20"
"02-May-20"
"03-May-20"
"04-May-20"
"05-May-20"
"06-May-20"
error encounter below
Error using datetime (line 667)
Unable to convert the text to datetime using the format 'dd/MM/yy'.
Error in Q3 (line 13)
dates=datetime(dates,'InputFormat','dd/MM/yy'); %convert date strings to date time format
댓글 수: 0
답변 (2개)
Voss
2024년 10월 2일
Looks like the format is 'dd-MMM-yy' rather than 'dd/MM/yy'.
dates=datetime(dates,'InputFormat','dd-MMM-yy')
댓글 수: 0
dpb
2024년 10월 2일
편집: dpb
2024년 10월 2일
@Voss showed you what was wrong in converting the dates -- your input format didn't match the actual format of your data. datetime is very picky; not only do the fields have to match the specific portion of the date or time string, the punctuation must match that used in the input string exactly as well.
However, MATLAB has better tools for handling and computing such than having to do it from basics -- the timetable is one convenient way with its builtin retime function--
Date=datetime(string(raw.textdata(2:end,1)),'InputFormat','dd-MM-yy');
ttData=timetable(Date,Production,T_Consumption,O_Consumption);
ttSums=retime(ttData,'monthly',@sum);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!