Working in Django I have a date range submitted on a form like this:
<input type="text" id="formGroupExampleInput" placeholder="Example input" name="daterange" value="02/01/2022 - 02/15/2022" />
I am passing this to a view and want to split out the from and to dates so that I have a 'date_from' and 'date_to' that I can work with.
This is my view:
from datetime import datetime
from django.shortcuts import render, get_object_or_404
from vans.models import Van
def booking(request):
"""This view returns the booking form page"""
return render(request, 'booking/booking.html')
def add_to_cart(request, item_id):
"""Adds the van booking to the cart"""
van = get_object_or_404(Van, pk=item_id)
# This will return the date range as a string
date_range_str = request.POST.get('daterange')
# In order to work with it I need it as two dates, date_from and date_to
return render(request, 'booking/cart.html')
CodePudding user response:
since you have a fixed format to receive the daterange what you can do is this in your views.py from datetime import datetime as dt
def add_to_cart(request, item_id):
"""Adds the van booking to the cart"""
van = get_object_or_404(Van, pk=item_id)
# This will return the date range as a string
date_range_str = request.POST.get('daterange')
date_range_lst = [data.strip() for data in date_range_str.split('-')]
date_from = date_range_lst[0]
date_to = date_range_lst[1]
# if you want to convert it to datetime object you can change it using:
date_from = dt.strftime(date_range_lst[0], '%m/%d/%Y')
date_to = dt.strftime(date_range_lst[1], '%m/%d/%Y')
return render(request, 'booking/cart.html')
CodePudding user response:
well you're in luck, pandas has a convent and aptly named function called pd.date_range
which takes a start
and end
date argument, as well as a frequency.
pd.date_range('01 Jan 2022', '05 Jan 2022', freq='D')
DatetimeIndex(['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04',
'2022-01-05'],
dtype='datetime64[ns]', freq='D')
each object is of a pandas._libs.tslibs.timestamps.Timestamp
type so you can apply any number of operations such as calculations or another.
What I would recommend is just creating a calendar table in your database that you can join to get your frequencies but I guess that's subjective.