Get hour of year from a Datetime
You can use timedelta
:
import datetime
dt = datetime.datetime(2019, 1, 3, 00, 00, 00)
dt2 = datetime.datetime(2019, 1, 1, 00, 00, 00)
print((dt-dt2).days*24)
output:
48
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.