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.
DATETIME_FORMAT="%Y-%m-%d%H:%M:%S"
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()
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With