In python, what I need is, given two dates;
i.e
date1 = '2021-11-03'
date2 = '2022-01-02'
I want to product a list of each day in between as a datetime object, so a list of
days_between = ['2022-01-01', '2021-12-31', '2021-12-30', etc, etc]
I also need to find the months between both, so in this case, I would want a list with say..
months_between = ['2022-01-01', '2021-11-01', '2021-12-01']
right now, i've been using something like this to accomplish this;
# Get all lessons
lessons = get_lessons_between(start=start, end=end, obj=True)
# Store the dates
dates = []
for lesson in lessons:
date = convert_to_dt_obj(lesson.date)
if date not in dates:
dates.append(date)
series = {}
for date in dates:
for lesson in lessons:
if convert_to_dt_obj(lesson.date) == date:
if lesson.date not in series.keys():
series[lesson.date] = lesson.value
else:
series[lesson.date] = lesson.value
tmp_lst = []
for k, v in series.items():
tmp_lst.append([k, v])
What i'm working is dates inside a database that are in string format 'YYYY-MM-DD'. I'm trying to normalize the data for some charting using APEX charts/vue on my frontend.
What I would prefer is to have the dates as a list between any two dates and just lookup in the database based on each one in the list so I could say..
for day in days_between:
.. do some database queries
any thoughts or help is appreicated.
CodePudding user response:
Partial answer (days only):
python3.9
Python 3.9.5 (default, Nov 23 2021, 15:27:38)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetimerange import DateTimeRange
>>> date1 = '2021-11-03'
>>> date2 = '2022-01-02'
>>> DateTimeRange(date1,date2).get_timedelta_second()/(3600*24)
60.0