how to read day of the year as datetime ?

조회 수: 12 (최근 30일)
pruth
pruth 2020년 7월 25일
답변: Star Strider 2020년 7월 25일
I have vector of dates, it looks like this
2019001
2019002
.
.
.
2019364
2019365
2019 is year and next number is day of the year.
anybody tell me how to use datenum or datetime here !
I have around 3 years of dara.

채택된 답변

per isakson
per isakson 2020년 7월 25일
편집: per isakson 2020년 7월 25일
>> chr = sprintf( '%d', 2019364 );
>> sdn = datenum(str2double(chr(1:4)),1,0)+str2double(chr(5:end));
>> datetime( sdn, 'ConvertFrom', 'datenum' )
ans =
datetime
30-Dec-2019 00:00:00
>>
Added later
%%
d = [ 2019001; 2019002; 2019364; 2019365 ];
%%
chr = num2str( d );
chr = strjust( chr, 'left' );
sdn = datenum( str2num(chr(:,1:4)), 1, 0 ) + str2num(chr(:,5:end));
dt = datetime( sdn, 'ConvertFrom', 'datenum' )
Outputs
dt =
4×1 datetime array
01-Jan-2019 00:00:00
02-Jan-2019 00:00:00
30-Dec-2019 00:00:00
31-Dec-2019 00:00:00

추가 답변 (2개)

madhan ravi
madhan ravi 2020년 7월 25일
v = regexprep(""+vector,'(\d{4})(\d+)','00/$2/$1');
Wanted = datetime(datestr(v))
  댓글 수: 2
madhan ravi
madhan ravi 2020년 7월 25일
Days_in_a_year = double(regexprep(v, '(\d+)/(\d+)/(\d+)', '$2'))
madhan ravi
madhan ravi 2020년 7월 25일
For older versions:
v = regexprep(sprintfc('%d',vector),'(\d{4})(\d+)','00/$2/$1'); % sprintfc() undocumented
Wanted = datetime(datestr(v))
Days_in_a_year = str2double(regexprep(v, '(\d+)/(\d+)/(\d+)', '$2'));

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


Star Strider
Star Strider 2020년 7월 25일
Another approach:
ydv = [2019001
2019002
2019364
2019365]; % ‘YearDay’ Vector
Years_Days = datetime(num2str(fix(ydv/1000)), 'InputFormat','yyyy') + caldays(rem(ydv,1000)-1)
producing:
Years_Days =
4×1 datetime array
01-Jan-2019
02-Jan-2019
30-Dec-2019
31-Dec-2019
Use the 'Format' name-value pair to get the desired output format. The easiest way to do that (for one example) is simply:
Years_Days.Format = 'yyyy-MM-dd';
to get:
Years_Days =
4×1 datetime array
2019-01-01
2019-01-02
2019-12-30
2019-12-31
.

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by