How to create a list of days starting with today and going back the last 30 days in Python

2 Answers

0 votes
from datetime import datetime, timedelta

def get_last_30_days():
    # Create a list to store the days
    days = []
    
    # Get today's date
    today = datetime.now()
    
    # Loop through the last 30 days
    for i in range(30):
        past_date = today - timedelta(days=i)  # Subtract 'i' days
        days.append(past_date.day)            # Add the day of the month to the list
    
    return days


# Get the last 30 days
days = get_last_30_days()
    
print("Days: [", end="")
print(", ".join(map(str, days)), end="")
print("]")



'''
run:

Days: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12]

'''

 



answered Apr 10, 2025 by avibootz
0 votes
from datetime import datetime, timedelta

# Get today's date
today = datetime.today()

# Generate a list of the last 30 days including today
last_30_days = [(today - timedelta(days=i)).strftime('%d') for i in range(30)]

for day in last_30_days:
    print(day)



'''
run:

10
09
08
07
06
05
04
03
02
01
31
30
29
28
27
26
25
24
23
22
21
20
19
18
17
16
15
14
13
12

'''

 



answered Apr 10, 2025 by avibootz
...