'In Python I want to parse a date range from a string to get a date_from and date_to
Working in Django I have a date range submitted on a form like this:
<input type="text" class="form-control vans-dates-form-input" 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')
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Umar.H |
