Algün Mandil
Algün Mandil

Reputation: 3

How can I convert string of dateTime to dateTime

takeDate is (Dec. 23, 2020, 8:23 p.m.), I want to change it to DateTime.

Editor Note: Would like to define a URL with variable from which a DateTime object can be created.

urls.py

from django.urls import path

from Reservations import views

urlpatterns = [

    path('rent/<takeDate>/<returnDate>/<id>', views.rent, name='rent'),
    
]

views.py

def rent(request, takeDate, returnDate,id):
    
    print(takeDate)
    return render(request, 'reservations/rent.html')

Upvotes: 0

Views: 169

Answers (1)

GTBebbo
GTBebbo

Reputation: 1218

You're better off defining the URL more explicitly to specify the format of the DateTime URL input. Have a look at this, a similar question although using an old version of Django.

Simple

If you define your URL knowing the date format you want to receive, you can easily convert to a datetime:

url_patterns = [
    path("rent/<int:take_day>-<int:take_month>-<int:take_year>/<int:return_day>-<int:return_month>-<int:return_year>/<id>/"),
]

Here we have a route that will match numerical dates in the format day-month-year.

Then in your view function, you can grab the arguments like normal and convert them into a DateTime:

from datetime import datetime

def rent(request, take_day, take_month, take_year, return_day, return_month, return_year, id):
    takeDateTime = datetime(take_year, take_month, take_day)
    returnDateTime = datetime(return_year, return_month, return_day)
    # ...

If you want to add in a time, you can keep adding to the URL pattern eg. (format: day-month-year-hour:minute)

"<int:take_day>-<int:take_month>-<int:take_year>-<int:take_hour>:<int:take_minute>"

Advanced

An even better solution, although more advanced is to use a custom path converter, you can read more about them in the Django docs: https://docs.djangoproject.com/en/3.1/topics/http/urls/#registering-custom-path-converters

I won't explain how to implement them here, as the Django docs will do a better job than me if you are interested in this method.

Upvotes: 1

Related Questions