Stream: helpdesk (published)

Topic: How many hours in a year?


view this post on Zulip Fons van der Plas (Sep 05 2022 at 09:54):

Hey! :raised_hands: Can I use the Dates stdlib to calculate the number of hours in a year?

view this post on Zulip Sebastian Pfitzner (Sep 05 2022 at 09:55):

which year? :stuck_out_tongue:

view this post on Zulip Fons van der Plas (Sep 05 2022 at 09:56):

2022!

view this post on Zulip Fons van der Plas (Sep 05 2022 at 09:58):

ooh thanks that helped me find the answer:

julia> dt = DateTime(2023,1,1) - DateTime(2022,1,1)
31536000000 milliseconds

julia> Hour(dt)
8760 hours

view this post on Zulip Fons van der Plas (Sep 05 2022 at 09:59):

I was trying

julia> Hour(Year(1))
ERROR: MethodError: Cannot `convert` an object of type Year to an object of type Hour

but I guess this is impossible because of leap years?

view this post on Zulip Sukera (Sep 05 2022 at 10:04):

yup

view this post on Zulip Sukera (Sep 05 2022 at 10:05):

but your calculation does the right thing

view this post on Zulip Sukera (Sep 05 2022 at 10:06):

julia> hoursinyear(y) = Hour(DateTime(y+1,1,1) - DateTime(y,1,1))
hoursinyear (generic function with 1 method)

julia> hoursinyear(2022)
8760 hours

julia> hoursinyear(2000)
8784 hours

julia> hoursinyear(2100)
8760 hours

view this post on Zulip Jeffrey Sarnoff (Sep 06 2022 at 14:12):

julia> using Dates

julia> const HoursPerDay = 24;

julia> yearhours(yr) = HoursPerDay * daysinyear(yr)
yearhours (generic function with 1 method)

julia> map(yr->Pair(yr, yearhours(yr)), 2020:2024)
5-element Vector{Pair{Int64, Int64}}:
 2020 => 8784
 2021 => 8760
 2022 => 8760
 2023 => 8760
 2024 => 8784

Last updated: Dec 28 2024 at 04:38 UTC