Time in order by AM and PM

I have an app that displays records from a database on a web page in date/time order, but when it lists them, it sorts by date and then seems to sort by the first number in the time field (example: 2020-06-20 06:00 PM then 2020-06-20 10:00 AM). Is there a way to get the AM times to appear before the PM times?

It depends upon how you’re storing the data in the database and where you’re doing the sort.

If you’re storing the date / time as a datetime field, and using the order_by clause to sort the data in your query, it should work correctly - this shouldn’t be an issue.

That you’re asking about this leads me to believe you’re handling this differently.

I am storing the date and time as CharField, because I think I ran into other issues storing them as datetime.

I will update the model to store them appropriately and see if that helps.

Thanks for the response.

And now I know why I didn’t use Date and Time fields. Here is my new Model:

class Reservation(models.Model):
name = models.CharField(max_length=200)
date = models.DateField(max_length=100)
time = models.TimeField(max_length=100)

class Meta:
	constraints = [
	models.UniqueConstraint(fields=['date', 'time'], name='unique_dt')]

def __str__(self):
	return self.name + " | " + str(self.date) + " | " + str(self.time)

In my code, I want the date and time to be unique together (someone can’t choose the same date and time as someone else). So when I enter information to save a record, every time I try to save it, I receive an error message that I generate, so that tells me it thinks that date/time combination exists in the database when I know for a fact that it doesn’t. This code works accurately using CharField, but then I run into the AM/PM issue.

They shouldn’t be two separate fields. You should have one datetime field, that you then extract the appropriate components as necessary when putting your views together.

That makes sense. The only reason I separated them is so a user can pick a date and then pick a time on the same form.

That’s fine - they don’t need to be the same field/widget. When building your form, you define two form fields that are populated from the database field when the form is created, and joined together when the form is submitted.

That makes sense. I will give that a try. Thanks for the great information and tips.

You want this form field: https://docs.djangoproject.com/en/3.0/ref/forms/fields/#django.forms.SplitDateTimeField

1 Like

Awesome! Thanks for the information.