How do i reach to hours in datetime

Question:

from datetime import datetime

today = datetime.today()
random_date = datetime(2022, 6, 19, 12, 37, 54)
time = today - random_date

print(time.hours)

How do I find how many hours have passed since random_date in this code?

Asked By: CB developer

||

Answers:

If I understood correctly, you may want to do this:

from datetime import datetime

today = datetime.today()
random_date = datetime(2022, 6, 19, 12, 37, 54)
time = today - random_date

# Use x2 slashes '//' in the division in order to get 
# an exact value 
print(time.total_seconds() / 3600)

Source: How do I convert datetime.timedelta to minutes, hours in Python?

Datetime docs: https://docs.python.org/3/library/datetime.html

Note: You can also use x2 slashes ‘//’ in the division in order to round the number to floor.

Answered By: Luka Cerrutti
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.