Q:

Get hour of year from a Datetime

Is there a simple way to obtain the hour of the year from a datetime?
dt = datetime(2019, 1, 3, 00, 00, 00) # 03/01/2019 00:00
dt_hour = dt.hour_of_year() # should be something like that

Expected output: dt_hour = 48
It would be nice as well to obtain minutes_of_year and seconds_of_year

A:

One way of implementing this yourself is this:
def hour_of_year(dt): 
    beginning_of_year = datetime.datetime(dt.year, 1, 1, tzinfo=dt.tzinfo)
    return (dt - beginning_of_year).total_seconds() // 3600

This first creates a new datetime object representing the beginning of the year. We then compute the time since the beginning of the year in seconds, divide by 3600 and take the integer part to get the full hours that have passed since the beginning of the year.
Note that using the days attribute of the timedelta object will only return the number of full days since the beginning of the year.

