Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django datefield and timefield to python datetime

I have a Django model with separate Datefield and Timefield for an event. Is there a way to convert it to a python datetime object so I can query for the upcoming events with some precision? Currently I get only the upcoming of the following day.

models.py

event_time = models.TimeField()
event_date = models.DateField()

Basically, can I filter with a minute, or even split second precition?

Thank you.

like image 835
freethrow Avatar asked Mar 31 '12 08:03

freethrow


People also ask

What is the format of datetime in Django?

DATETIME_FORMAT="%Y-%m-%d%H:%M:%S"

How do I change the default date in Django?

If you want to be able to modify this field, set the following instead of auto_now_add=True : For DateField : default=date.today - from datetime.date.today() For DateTimeField : default=timezone.now - from django.utils.timezone.now()

What is Auto_now_add in Django?

From django docs: “”" auto_now Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it's not just a default value that you can override. auto_now_add Automatically set the field to now when the object is first created.


1 Answers

Use a DateTimeField instead (see this section in the docs). Conversion to a datetime.datetime is handled for you by Django automatically.

A DateField results in a datetime.date and a datetime.time object. You can use replace to merge these values into an updated date:

>>> today = datetime.datetime.today()
>>> today
datetime.datetime(2012, 3, 31, 11, 6, 5, 182371)
>>> time = datetime.time(11, 30)
>>> today.replace(hour=time.hour, minute=time.minute)
datetime.datetime(2012, 3, 31, 11, 30, 5, 182371)

Note that the resulting date has 11.30 as time now. Note also that today is not modified, it simply computes a new date and time. As you can see, you now have to do the merging yourself because both values are stored in separate fields. That's why a DateTimeField is a much better choice, if you have the ability to modify the model's fields.

like image 177
Simeon Visser Avatar answered Sep 28 '22 12:09

Simeon Visser