0

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

codyc4321
  • 9,014
  • 22
  • 92
  • 165
  • 2
    You have your date difference calculation the wrong way around, hence the -1 day. It should be `now - stock.last_updated_time.replace(tzinfo=None)` because now should be greater than the last updated time – 0sVoid Aug 15 '22 at 08:28
  • aha time delta always confused me. let me try that correction – codyc4321 Aug 15 '22 at 08:39
  • 2
    Also you could use `ast_updated_time = models.DateTimeField(null=True, auto_now=True)`. The auto_now argument automatically updates the field every time an instance is saved, so you don't need custom functions for handling your update TimeField. – Val Berthe Aug 15 '22 at 08:54
  • 1
    I also believe that the comparison itself is the other way around. If the timedelta is *lower* than one minute then consider that the stock was updated recenlty. Else if the timedelta is *greater* than one minute, consider that you can make an API call. – Val Berthe Aug 15 '22 at 09:00
  • yes ty val i believe i had to also swap the caret in the final answer – codyc4321 Aug 15 '22 at 11:06

2 Answers2

1

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.

0sVoid
  • 2,547
  • 1
  • 10
  • 25
0
        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)
codyc4321
  • 9,014
  • 22
  • 92
  • 165