Home > Net >  List past hours of today with django
List past hours of today with django

Time:03-22

How do I create a list of past hours of the day?

I tried this but it only gets the past 12 hours, and what if the past hour is from yesterday?

past_hours = []
for x in range(12):
past_hours.append((date - datetime.timedelta(hours=x)))

CodePudding user response:

This may be what you're after:

import datetime

now = datetime.datetime.now()
day = now.day
month = now.month
year = now.year

hours_since_midnight = now.hour
hours = []

# Via a for loop
for i in range(hours_since_midnight):
    hours.append(datetime.datetime(year, month, day, hour=i))

# Or you can do it this way (list comprehension)
hours = [datetime.datetime(year, month, day, hour=x)
         for x in range(hours_since_midnight)]

This will create a list of date-times of the start of every hour since the start of the day (not including the current hour). If you want the current hour, you need to do range(hours_since_midnight 1)

  • Related