Home > Enterprise >  check if model was recently updated fails trying to use timedelta
check if model was recently updated fails trying to use timedelta

Time:08-15

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

CodePudding user response:

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.

CodePudding user response:

        the_timedelta = now - stock.last_updated_time.replace(tzinfo=None)
        print(the_timedelta)
        # https://stackoverflow.com/questions/12484003/what-is-the-best-way-to-check-if-time-is-within-a-certain-minute
        if the_timedelta < datetime.timedelta(minutes=5):
             print("stock was updated within the last 5 minutes...no need to make an api call")
             current_price = stock.current_price
        else:
            print("stock hasn't been updated recently, make api call")
            current_price = get_recent_price_or_database_saved_price(ticker=ticker, stock=stock)
  • Related