Indexing by year from full date

6 views (last 30 days)
I'm working with a data set that provides the date in two ways, yyyymmdd (bot_date) and decimal years (bot_decy). I need to be able to index the data by year (and month) but I'm having trouble separating the dates into year, month, and day.
[bot_yr bot_mon bot_day bot_hr bot_min bot_sec]=datevec(bot_decy);
bot_V=datevec(bot_decy);
%ConvertSerialYearToDate(bot_decy);
%[bot_yr bot_mon bot_day bot_hr bot_min bot_sec]=datevec(bot_decy);
%bot_V=datevec(bot_decy);
%BD=datevec(bot_decy);
function [num] = ConvertSerialYearToDate( y )
year = floor(y);
partialYear = mod(y,1);
date0 = datenum(num2str(year),'yyyy');
date1 = datenum(num2str(year+1),'yyyy');
daysInYear = date1 - date0;
num = date0 + partialYear .* daysInYear;
end
These three ways have given me an table like this.
[bot_yr bot_mon bot_day]=datevec(bot_date);
bot_V=datevec(bot_date);
datevec(bot_yr);
This way gives me a weird number for the year (54432 instead of 1988). I've tried it several different ways and I keep getting stuck at these two ends, the table and the weird year.

Accepted Answer

Cris LaPierre
Cris LaPierre on 18 Nov 2020
I'd convert your dates to datetimes. Then you can just use the year, month, and day functions.
  1 Comment
Steven Lord
Steven Lord on 18 Nov 2020
There's also the ymd function that returns those three quantities in one function call.
But if you have time- and date-based data I'd consider storing it in a timetable array. If you do, using retime to aggregate data based on the date and/or time or using a timerange to index into it could be useful.
MeasurementTime = datetime({'2015-12-18 08:03:05'; ...
'2015-12-18 10:03:17'; ...
'2015-12-18 12:03:13'});
Temp = [37.3;39.1;42.3];
Pressure = [30.1;30.03;29.9];
WindSpeed = [13.4;6.5;7.3];
WindDirection = categorical({'NW';'N';'NW'});
TT = timetable(MeasurementTime,Temp,Pressure,WindSpeed,WindDirection)
TT = 3x4 timetable
MeasurementTime Temp Pressure WindSpeed WindDirection ____________________ ____ ________ _________ _____________ 18-Dec-2015 08:03:05 37.3 30.1 13.4 NW 18-Dec-2015 10:03:17 39.1 30.03 6.5 N 18-Dec-2015 12:03:13 42.3 29.9 7.3 NW
ten = datetime(2015, 12, 18, 10, 0, 0);
tenToEleven = timerange(ten, ten + hours(1))
tenToEleven =
timetable timerange subscript: Select timetable rows with times in the half-open interval: [18-Dec-2015 10:00:00, 18-Dec-2015 11:00:00) See Select Timetable Data by Row Time and Variable Type.
TT(tenToEleven, :)
ans = 1x4 timetable
MeasurementTime Temp Pressure WindSpeed WindDirection ____________________ ____ ________ _________ _____________ 18-Dec-2015 10:03:17 39.1 30.03 6.5 N

Sign in to comment.

More Answers (0)

Categories

Find more on Dates and Time in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!