How to compare a datetime to datetimes stored in a Django model?

I have a Django model as follows that includes version_date, which is a DateTimeField:

class Flow(models.Model):
    name = models.CharField(max_length=30, choices=FLOW_NAMES)
    version = models.PositiveSmallIntegerField()
    version_date = models.DateTimeField()
    file = models.FileField(blank=True,null=True)
    last_accessed = models.DateTimeField(auto_now=True)

I would like to compare a timestamp which I have extracted from a XML file, to each version_date value stored in the model. How can I iterate through the model comparing the extracted timestamp to each version_date in the model?

Made an xml file with datetime=2022-05-30 14:15:00. This is what its content looks like:

<first one="1"><id>2022-05-30 14:15:00</id></first>

The file is located in the folder where is. In the "test" view, the file is read and the root[0].text subelement is used. The value of which is converted to datetime(qqq). Next, the qrt variable is set to values greater than or equal to "qqq" using gte. And a list of filtered "version_dates" is created, which are displayed on the page. Also, all "version_date" data is printed in the loop, you can comment out or delete these lines. In this case, in my database:

2022-06-15 12:00:00+00:00
2022-06-01 06:00:00+00:00
2022-05-05 12:06:27+00:00

from django.urls import path
from .views import test

urlpatterns = [
    path('test/', test),


from .models import Flow
from django.http import HttpResponse
import xml.etree.ElementTree as ET
import datetime

def test(request):
    tree = ET.parse('aaa.xml')
    root = tree.getroot()

    format = '%Y-%m-%d %H:%M:%S'
    qqq = datetime.datetime.strptime(root[0].text, format)

    for e in Flow.objects.all():#you can remove these two lines, they print all version_date
        print(e.version_date)#you can remove these two lines, they print all version_date

    qrt = Flow.objects.filter(version_date__gte=qqq)
    qrt_list = [qrt[i].version_date for i in range(len(qrt))]

    return HttpResponse(f"<p>version_date: {qrt_list}</p>")
Back to Top