Making a datetime vector with a leap year

3 ビュー (過去 30 日間)
Joel
Joel 2023 年 4 月 5 日
コメント済み: Steven Lord 2023 年 4 月 5 日
Hi all
I have some code making a 8760x1 datetime vector containing every hour of the year
dt = datetime(2021,1,1:365);
et = hours(0:23)';
t = repmat(dt,length(et),1) + repmat(et,1,length(dt));
t=t(:);
'01-Jan-2021 00:00:00'
'01-Jan-2021 01:00:00'
'01-Jan-2021 02:00:00'
'01-Jan-2021 03:00:00'
'01-Jan-2021 04:00:00'
'01-Jan-2021 05:00:00'
'01-Jan-2021 06:00:00'
'01-Jan-2021 07:00:00'
'01-Jan-2021 08:00:00'
However some years are leap years. So if it is a leap year I want the 29 of February to be inserted properly. Like:
if length(Data{:,1})==422 %regular year
dt = datetime(2021,1,1:365);
et = hours(0:23)';
t = repmat(dt,length(et),1) + repmat(et,1,length(dt));
t=t(:);
elseif length(Data{:,1})==423 %leap year
"The code I am asking for"
end

回答 (2 件)

Fangjun Jiang
Fangjun Jiang 2023 年 4 月 5 日
編集済み: Fangjun Jiang 2023 年 4 月 5 日
Do it directly by specifying the starting and ending datetime.
d1=datetime(2021,1,1,0,0,0);
d2=datetime(2021,12,31,23,0,0);
size(d1:hours(1):d2)
ans = 1×2
1 8760
  3 件のコメント
Les Beckham
Les Beckham 2023 年 4 月 5 日
Yes, a leap year does have 8784 hours. But 2021 is not a leap year. 2024 is:
d1=datetime(2024,1,1,0,0,0);
d2=datetime(2024,12,31,23,0,0);
size(d1:hours(1):d2)
ans = 1×2
1 8784
Steven Lord
Steven Lord 2023 年 4 月 5 日
2021 was not a leap year. But as an example, 2020 was a leap year.
y = 2020;
d1=datetime(y,1,1,0,0,0)
d1 = datetime
01-Jan-2020
d2=datetime(y,12,31,23,0,0)
d2 = datetime
31-Dec-2020 23:00:00
size(d1:hours(1):d2)
ans = 1×2
1 8784
Another way to create d2 would be to shift d1 to the start of the next year then subtract an hour. This way the year information only appears in one place in the code, in the definition of d1.
d2Alternate = dateshift(d1, 'start', 'year', 'next') - hours(1)
d2Alternate = datetime
31-Dec-2020 23:00:00
d2 == d2Alternate
ans = logical
1

サインインしてコメントする。


Stephen23
Stephen23 2023 年 4 月 5 日
編集済み: Stephen23 2023 年 4 月 5 日
D = datetime(2021,1,1);
V = D:hours(1):D+calyears(1)-minutes(1);
size(V)
ans = 1×2
1 8760
D = datetime(2020,1,1);
V = D:hours(1):D+calyears(1)-minutes(1);
size(V)
ans = 1×2
1 8784

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

製品


リリース

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by