Save dutch date - django

I have an input field with the following value: 12-04-2012
This is a Dutch date that I want to save in the database. Database Field is Date.
How can I save a non English date into the database?
I tried:
HTML
<input id="id_delivery_date" type="text" value="12-04-2012" name="delivery_date">
DJANGO
def save(self, user, session):
self.order.delivery_date = self.cleaned_data['delivery_date']
self.order.save()

You could use datetime.strptime to parse the string and create a datetime object that can directly be assigned to the database field.
from datetime import datetime
datetime.strptime('12-04-2012', '%d-%m-%Y')
Another option would be to use string processing, but this is quite a hack and not recommended.
>>> '-'.join(reversed('12-04-2012'.split('-')))
'2012-04-12'

By Dutch date, I assume you mean the format is MM-DD-YYYY. You can parse this into a datetime object with
from datetime import datetime
datetime.strptime("12-04-2012", "%d-%m-%Y")

Related

Django Changing Date Input Format

I have a simple booking form which is having a date input in a line like:
reservation.html
<textarea name="booking" class="form-control" id="reservation"
value="{{placement.date|date:'d/m/Y'}}"></textarea>
models.py
class Lib(models.Model):
booking = models.DateField(null=True, blank=True)
My database postgresql based and also store date as in "date" format. I would love to change date-input like dd/mm/yyyy
I also tried to use placement.date|date type format in double quotes like:
<textarea name="booking" class="form-control" id="reservation"
value="{{placement.date|date:"d/m/Y"}}"></textarea>
But its still accept as mm/dd/YY. Is there any problem about my placement? My forms.py kinda simple like:
from django.forms import ModelForm
from .models import Lib
from django.utils import formats
class LibForm(ModelForm):
class Meta:
model = Lib
fields = ['title','name','email','booking']
I searched on google and on stackoverflow and found something on Django - Setting date as date input value and django how to format date to DD/MM/YYYY but i couldn't find anything that could help me. I have to seek help here as a last resort. Thanks in advance.

How can I convert the DateTimeField in Django from UTC to enduser's timezone (usually PST) when querying a Django model?

I'm querying a Django model connected to a table in my Postgres database that contains a datetime stored in UTC.
My query code looks something like this:
query_set = table_object.objects.values()
One of the columns in the query set is the datetime value in UTC.
The model looks like this:
class ops_inbox_view(models.Model):
requested_date = models.DateTimeField()
other_item = models.CharField(max_length=20)
other_item2 = models.CharField(max_length=40)
other_item3 = models.CharField(primary_key=True, max_length=10)
other_item4 = models.CharField(max_length=50)
other_item5 = models.CharField(max_length=50)
other_item6 = models.CharField(max_length=50)
I want to convert this into PST or robustly in the enduser's local time zone. My current solution is to use pandas with dt.tz_localize and dt.tz_convert after loading the query set into a dataframe but I'm trying to find a solution that is easily manageable in one location of the project file structure of the app. In my settings.py, I have TIME_ZONE set to 'US/Pacific' but because I'm using Pandas, the conversion to PST is not automatically done and will have to change many lines of code in my views.py to make the conversion with pandas.
Is there a way to not use Pandas and instead either make the field timezone aware or make the explicit conversion in the query code? Also looking for any other best practices in timezone management and display. Serving this datetimefield into an html file...
You can use F() with annotate
from datetime import timedelta
from django.db.models import DateTimeField, ExpressionWrapper, F
table_object.objects.annotate(modified_date=ExpressionWrapper(F('requested_date')+timedelta(minutes=960), output_field=DateTimeField())).filter(modified_date='2019-11-30')
Here you need to +/- minutes to convert utc datetime to your(PST) timezone and it will store converted dates into modofied_date, after that we can filter it.
Note:
You don't need to use pandas to convert timezones. Django good built-in timezone management tools.
Their timezone docs are quite good as well, so I'd suggest reading it all the way through.
The problem you're havingĀ seems very similar to one described in their docs

Django change the way date field is displayed in django admin

That's it i want to change the way its displayed cause it says "noon" or "midnight" and i want i to display the exact hour
I've got this code on the field
date = models.DateTimeField(auto_now_add=True, default=datetime.date.today())
You have 3 options.
Override DATETIME_FORMAT, read here: datetime format
Use a form for your model and in the date attribute have some like this(
in input format, put whatrever you want):
date = forms.DateTimeField(input_format="%b %d %Y %I:%M%p")
Or just change the way you render your datetime field in the template:
{{ your_model.date_field|date:'Y-m-d H:i' }}

Django - Date and Time Field Explanation

I have few questions regarding the Date and time fields both in the model and in the form class.
1.)In the docs for the date field what does the line "Normalizes to: A Python datetime.date object." mean? Does it mean that the field data stored in the request.POST dictionary on the submission of the form is a datetime.date object?If yes, then when does it do it when the form is submitted or do we have to call one of its functions?
2.)If i have a models.DateField() then while assigning data to it manually in a view should i assign a datetime.date object or a unicode object with the 'yyyy-mm-dd' format?
3.)If i take a date in my forms.DateField() in the '%d/%m/%y' format how do i assign it to my models.DateField() because that seems to accept only the 'YYYY-mm-dd' format?
If somebody could also suggest some links which explain these fields in detail with examples apart from the docs it would be helpful.
For first question, datefield saves date object and if you are saving any data( for example a string: "01-01-2015") to datefield, then you have to convert that data into date object. You will not get a date object in request.POST, if you use a form, then you can get it by using cleaned_data.(example below) From request.POST ,you will get an unicode object.( then you will need to convert it to date object, example below)
For second question, obviously you have to save dateobject, not unicode object.
For third question, in forms, To display initial field value properly formatted, use DateInput widget. To customize validation, use input_formats keyword argument of DateField. Here, from forms, you will get a date object in views, so it can be saved directly, like:
In model.py:
class DateModelClass(models.Model):
date= models.DateField()
In forms.py:
date= forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=('%d/%m/%Y',))
In views.py:
date_data= DateModelClass(date= form.cleaned_data['date'])
date_data.save()
Also you can convert a string of your desired format to Date Object like this:
>>import datetime
>>datetime.datetime.strptime(u"09/07/2014", '%d/%m/%Y').date()

Search DateFields by Format A in Django Admin though they are stored in Format B

Am building a Django app. And on the admin is is required to be able to search for items based on queries that might also include names of the month, year, etc.
The problem (I can't seem to find a solution to this on SO or elsewhere), is that the default format for dates in Django (ok, the way the dates have been persisted to the datastore) is %Y-%m-%d, but I wish to be able to search on say query like "June" from the Django Admin search.
How do I make it possible to search date fields using custom date formats, without converting the formats in which the dates are persisted?
Date and Time are stored in the database as a distinct type for them, because you should be able to do special date time operations like greater than, lesser than and not just string search.
Django ORM accepts the date-time as strings formatted in one of the standard formats including strings, integers and datetime objects .
Example:
Entry.objects.filter(pub_date__year=2006)
or
Entry.objects.filter(
... headline__startswith='What'
... ).exclude(
... pub_date__gte=datetime.now()
... ).filter(
... pub_date__gte=datetime(2005, 1, 1)
... )
You could use any one of the several libraries to parse the time in the string to datetime
objects. The easiest would be to use the awesome dateutil library:
import dateutil.parser
dateutil.parser.parse('2008-08-09T18:39:22Z')
#Following is returned
datetime.datetime(2008, 8, 9, 18, 39, 22, tzinfo=tzutc())
You've probably already found the answer but it could be useful to someone (like myself!) still looking into this.
Django 1.6+ :
You can customise the search results:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_search_results
Previous Django versions:
You just need to use your own ChangeList to temporary change the date format in the query string. Note that the format is only changed temporarily so that the user won't see any change in the query string.
The example here below accepts UK date format, e.g. '31 Dec 1999' but it can easily changed to accept any date format (or just a month name like 'June' as requested by #nemesisfixx)
In your admin model customise the changelist class:
class MyModelAdmin(admin.ModelAdmin):
...
def get_changelist(self, request, **kwargs):
"""
Returns the ChangeList class for use on the changelist page.
"""
return MyChangeList
Then in MyChangeList class:
class MyChangeList(ChangeList):
def get_query_set(self, request):
# Allow date search with UK format
try:
date_search = datetime.datetime.strptime(self.query, '%d %b %Y').date().strftime('%Y-%m-%d')
except ValueError:
date_search = self.query
with temporary_value(self, 'query', date_search):
qs = super(MyChangeList, self).get_query_set(request)
return qs