Python Forum

Full Version: Make list of dates between today back to n days
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I want to make list of dates from now back to n days (for example 2 days) with time interval 12hrs.

I use the bewlow code, but its giving me empty.

from datetime import date, datetime, timedelta
def datetime_range(start, end, delta):
    current = start
    print(current)
    if not isinstance(delta, timedelta):
        delta = timedelta(delta)
    while current < end:
        yield current
        current += delta


interval=12 #12hrs
n_days=2
start = date.today()
end=start_dt-timedelta(days=n_days)
dates_list =[]
for dt in datetime_range(start, end,interval):
    dt_m = (dt-timedelata(hours=12)).strftime("%Y-%m-%d %H:%M:%S")
    dates_list.append(dt_m)
my desired output is: for example time now is 2020-10-01 18:10:10

my_list of dates:

[2020-09-29 18:10:10 2020-09-30 06:10:10 2020-09-30 18:10:10 2020-10-01 06:10:10 2020-10-01 18:10:10]
Are you sure it giving 'empty' and not 'NameError'?

There is no 'start_dt' and there is 'timedelata' as well. There is no way you can get empty list from this snippet.

EDIT: and there is difference between today and now :-)
I corrected, but still give empty (no error)

from datetime import date, datetime, timedelta
def datetime_range(start, end, delta):
    current = start
    print(current)
    if not isinstance(delta, timedelta):
        delta = timedelta(delta)
    while current < end:
        yield current
        current += delta


interval=12 #12hrs
n_days=3
start = date.today()
end=start-timedelta(days=n_days)
dates_list =[]
for dt in datetime_range(start, end,interval):
    dt_m = (dt-timedelata(hours=12)).strftime("%Y-%m-%d %H:%M:%S")
    dates_list.append(dt_m)

print(dates_list)
You want to use an interval of 12 hours. So you must calculate with datetime, not date. You can leave date out from the import.

In line 6 you must make clear you delta is the number of hours:
delta = timedelta(hours=delta)
The while on line 7 is upside down:
    while current < end:
        yield current
        current += delta
But you are counting down. So it must be:
    while current > end:
        yield current
        current -= delta
As we are calculating in datetime you must change line 14, instead of date.today() it must be:

start = datetime.now()
In line 18 you must correct a typo: "timedelata" must be "timedelta".
Output:
2020-10-03 14:22:09.268970 ['2020-10-03 02:22:09', '2020-10-02 14:22:09', '2020-10-02 02:22:09', '2020-10-01 14:22:09', '2020-10-01 02:22:09', '2020-09-30 14:22:09']