I am trying to convert the date data from the CSV file to datetime, but it shows error, how do I fix this
3 ビュー (過去 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!