Django datefield and timefield for python datetime

I have a Django model with a separate date and time field for an event. Is there a way to convert it to a python datetime object so that I can request upcoming events with some accuracy? Currently, I only receive the upcoming next day.

models.py

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

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

Thanks.

+6
source share
2 answers

Use DateTimeField instead (see this section in the docs). Converting to datetime.datetime is done automatically for Django.

A DateField results in a datetime.date and a datetime.time object. You can use replace to combine 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 now has 11.30. Also note that today not changing, it just calculates the new date and time. As you can see, now you need to merge yourself, because both values โ€‹โ€‹are stored in separate fields. This is why DateTimeField is a much better choice if you have the ability to modify model fields.

+9
source

You add a new field, for example, a datetime merge field. Better for performance.

 event_full_datetime = models.DateTimeField() 

fix the old database. for a shell like a 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() 
+4
source

Source: https://habr.com/ru/post/912106/


All Articles