How to get date time based start value and end value in python


I have string period = 2022-09-12/2022-09-15

How can i get arr = [2022-09-12, 2022-09-13, 2022-09-14, 2022-09-15]


Asked By: Quang Linh



You can do it like this:

start_date = datetime.datetime(2022, 9, 12)
end_date = datetime.datetime(2022, 9, 15)

involved_dates = []
for i in range((end_date - start_date).days):
    involved_dates.append(start_date + datetime.timedelta(days=i))
Answered By: Oleksandr Lisovyi

Since you didn’t specify what part of the problem you’re struggling with, here’s a solution for the whole thing:

from datetime import datetime, timedelta

text = '2022-09-12/2022-09-15'

def date_range(start, end):
    # this function takes two dates and generates all the dates in the range
    for d in range((end - start).days + 1):
        yield start + timedelta(days=d)

# defining the format your dates come in (and in which you may want them)
format = '%Y-%m-%d'

# this is the answer, using the above function
dates = list(date_range(*map(lambda d: datetime.strptime(d, format), text.split('/'))))

# taking the `dates` result, you can of course format them as strings:
print([datetime.strftime(d, format) for d in dates])


[datetime.datetime(2022, 9, 12, 0, 0), datetime.datetime(2022, 9, 13, 0, 0), datetime.datetime(2022, 9, 14, 0, 0), datetime.datetime(2022, 9, 15, 0, 0)]
['2022-09-12', '2022-09-13', '2022-09-14', '2022-09-15']

On the key expression:

list(date_range(*map(lambda d: datetime.strptime(d, format), text.split('/'))))

The function is a generator, so there’s a list() around it to exhaust the generator into a list.

The map() takes a function, in this case a lambda and applies it to all elements of an iterable, in this case text.split('/'), which is just the two date strings in your original text.

The lambda takes those two parts and parses them into actual datetime using datetime.strptime(d, format), so the map() yields the two dates.

The * then spreads those into the function call to date_range(), providing the dates as arguments.

Note: if this also needs to work for a descending range of dates, for example '2022-09-15/2022-09-12', you can use this instead (which works for either):

def date_range(start, end):
    days = (end - start).days
    sign = -1 if days < 0 else 1
    for d in range(0, days + sign, sign):
        yield start + timedelta(days=d)
Answered By: Grismar
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.