DateTimeField to str and read from str - django

I have a problem with understating how to deal DateTimeField.
I have model with DateTimeField, view which returns jsons containing this field and another view which use provided data (as string) to filter result
# model
date = models.DateTimeField(auto_now=True)
# first view
return str((self.date.isoformat() for date in ...))
# f. exp: ['2019-11-19T15:22:47.788254+00:00']
# second view
Row.objects.filter(data__lte=data_from_GET)
If I have used 2019-11-19T15:22:47.788254+00:00 I reciver error
ValidationError at /csv/
["'2019-11-19T15:22:47.788254+00:00' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
I can not find an easy way (without string manipulation) to return data in a format acceptable by the filter method.
What is interesting:
2019-11-19T15:22:47.788254-00:00 not ok
2019-11-19 15:22:47.788254+00:00 not ok
2019-11-19 15:22:47.788254-00:00 ok

You could use EpochUTC and integer values to compare different dates. If you need to display these dates you can transform them into strings using the new Date constructor.

Related

Filtering objects by timezone aware dates

Let's say I have TIME_ZONE variable in settings set to 'Europe/Prague' and also USE_TZ set to True. I also have some data stored in Example:
id timestamp
1 2012-07-27T00:00:00+02:00
2 2018-03-11T02:00:00+01:00
3 2013-11-04T14:08:40+01:00
This is what I'm trying to achieve:
Extract all dates from those data
Filter those data date by date and perform some other action on them
For extracting dates I use either Example.dates('timestamp', 'day') or Example.annotate(date=TruncDay('timestamp')).values('date').
Now here is the difference: for first object from example above (with timestamp=2012-07-27T00:00:00+02:00), date returned by first approach is 2012-07-27, whereas for second approach it is 2012-07-26.
I would like filter to be timezone aware, so I'm currently sticking with the first one.
For filtering I am using Example.filter(timestamp__date=date). And there's a problem - it seems that __date filters by date converted to UTC. For date 2012-07-27 it returns empty QuerySet and for 2012-07-26 it returns first object.
Is there any way to achieve filtering by timezone aware date?

Parse european string date to Django DateField

I am using USE_L10N = True in my app settings. As I understood, this setting let Django adapt date format according to the user current locale.
So in the admin, my model that contains a DateField is correctly represented in the form with the format "%d/%m/%Y".
The problem I have is when I want to create a new object from my code. I have a CSVParse custom function parsing a CSVĀ file and creating objects. One of the column in the CSV has the same format as above ("17/12/2015" for instance). I tried to parse the date with the line below but it returns "None". In the documentation of date_parse, I can see that it means a wrong format.
from django.utils import dateparse
date_csv = "18/12/2014"
date = dateparse.parse_date(date_csv)
What am I missing?
Thanks
Django dateparse uses date_re (regex) for parse_date and date_re format is year-month-day
date_re = re.compile(
r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$'
)
The input you are giving is having format day/month/year hence you are getting None as result.
Check out strptime
import time
date_csv = "18/12/2014"
date = time.strptime(date_csv, "%d/%m/%Y")

Unable to retrieve data in django

I am writing a weblog application in django. As part of this, I have a view function that fetches an object from the database corresponding to a single blog post. The field that I am using to query the database is the published date (pub_date) which is of type DateTime (Python). I have a MySQL database and the type of the column for this field is datetime. But I am not able to fetch the object from the database though I am passing the correct date attributes. I am getting a 404 error.The following is my view function:
def entry_detail(request,year,month,day,slug):
import datetime,time
date_stamp = time.strptime(year+month+day,"%Y%b%d")
pub_date = datetime.date(*date_stamp[:3])
entry = get_object_or_404(Entry,pub_date__year=pub_date.year,pub_date__month=pub_date.month,pub_date__day=pub_date.day,slug=slug)
return render_to_response('coltrane/entry_detail.html',{'entry':entry})
The following is the URL of the individual post that I want to fetch:
http://127.0.0.1:8000/weblog/2014/oct/28/third-post/
And this is how the pub_date column value for the third-post in the database looks like:
2014-10-28 13:26:39
The following is the URL pattern:
url(r'^weblog/(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$','coltrane.views.entry_detail'),
You're doing some odd things here: you're converting to a time, then converting that to a datetime.date, then extracting the year, month and day as integers and passing them to the query. You could bypass almost the whole process: the only thing you need is to convert the month, the other parameters can be passed directly:
month_no = datetime.datetime.strptime(month, '%b').month
entry = get_object_or_404(Entry, pub_date__year=year, pub_date__month=month_no, pub_date__day=day, slug=slug)

Django Model DatetimeField without seconds

I want to enter date and time in my admin site with
date = models.DateTimeField()
But I dont want to have the seconds in my view. Is it possible to display the time like this:
10:45 instead of 10:45:00 ?
Yes you can:
https://docs.djangoproject.com/en/dev/ref/forms/fields/#datetimefield
input_formats
A list of formats used to attempt to convert a string to a valid datetime.datetime object.
If no input_formats argument is provided, the default input formats are:
Thats if you want to save as well with no seconds, If you only want to change how its displayed in your templates your can use the date template filter:
https://docs.djangoproject.com/en/1.6/ref/templates/builtins/#date

Retrieving only the date part of a datetime column in Django

I am a starter in Django/Python.
I have a model MyModel. It has many fields of datetime, char, integer types. Now, I want a values list which has values of the datetime fields containing only the date parts.
I have tried using the dates function [reference] (https://docs.djangoproject.com/en/1.2/ref/models/querysets/#dates), but it works only with one field. I have multiple datetime fields and all have to be retrieved in the required format.
Basically, I want a Django equivalent of :
select stringfield1, date(datefield1), integerfield1, date(datefield2) from mymodel; (PostGreSQL)
Is this even possible? If it is, how should I proceed further?
I'm not sure if Django has a builtin way of doing this. You could use itertools.imap to lazily convert the fields in question into date objects:
from itertools import imap
values = MyModel.objects.values_list('stringfield1', 'datefield1',
'integerfield1', 'datefield2')
values = imap(lambda (s, d1, i, d2): (s, d1.date(), i, d2.date()), values)
(But note that after this you're not dealing with a ValuesListQuerySet anymore but with an itertools.imap object.)