check if model was recently updated fails trying to use timedelta

Question:

I have the following model that saves a datetime on save:

class StockInfo(models.Model):
    ticker = models.CharField(max_length=100)
    current_price = models.FloatField()
    name = models.CharField(max_length=255)
    summary = models.TextField()
    sector = models.CharField(max_length=100)
    dividends = models.ArrayField(model_container=Dividend)
    last_updated_time = models.DateTimeField(null=True)

    objects = models.DjongoManager()

    # https://stackoverflow.com/questions/9953427/django-custom-save-model
    def save(self, *args, **kwargs):
        self.last_updated_time = datetime.datetime.now().astimezone()
        super(StockInfo, self).save(*args, **kwargs)

In the view I try using a timedelta to determine if the model had been updated within the last minute:

the_timedelta = stock.last_updated_time.replace(tzinfo=None) - now
print(the_timedelta)
if the_timedelta > datetime.timedelta(minutes=1):
    print("stock was updated within the last minute")
else:
    print("stock hasn't been updated recently")

I was expecting it to determine these rapid updates were within a minute:

found the stock
the last updated time for stock good before save: 08/15/2022 07:51:09
-1 day, 23:59:31.335919
stock hasn't been updated recently
the last updated time for stock good after save: 08/15/2022 07:51:38

reversing the comparison to if the_timedelta < datetime.timedelta(minutes=1): causes the opposite error:

the last updated time for stock stag before save: 08/15/2022 07:51:37
-1 day, 23:50:47.073490
stock was updated within the last minute
the last updated time for stock stag after save: 08/15/2022 08:00:50

I would like to be able to determine if the stock object was saved in the last 60 seconds and if so I don’t need to make another API request so soon

Asked By: codyc4321

||

Answers:

The reason that the timedelta comparison isn’t working as expected is the date difference calculation is the wrong way around, hence the -1 day result. It should be:

now - stock.last_updated_time.replace(tzinfo=None)

The now datetime should be greater than the last updated time and give an answer in just minutes/seconds that can be compared to timedelta.

Answered By: 0sVoid
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.