Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.


Solution 2:

You shoud add new field like a merge datetime field. Better for Performance.

event_full_datetime = models.DateTimeField()

fix old database. for shell like this script.

for obj in YourModel.objects.all():
    obj.event_full_datetime = datetime.datetime( obj.event_date.year,obj.event_date.month, obj.event_date.day, obj.event_time.hour,  obj.event_time.minut,  obj.event_time.second) 
    obj.save()

Solution 3:

If you need to store a NULL (unknown) time then you can use datetime.combine within a computed property:

from datetime  import datetime, time
from django.db import models

class Event( models.Model ):
  event_date = models.DateField()
  event_time = models.TimeField( null = True )

  @property
  def event_datetime( self ):
    """The combined event_date and event_time (or midnight if unset)."""
    return datetime.combine( self.event_date, self.event_time if self.event_time is not None else time.min )

Post a Comment for "Django Datefield And Timefield To Python Datetime"