Sobes.tech
Junior — Senior

Determining the nearest exchange rate for the specified date

livecode

Task condition

It is necessary to implement an API endpoint that accepts a date from the client and returns the currency exchange rate record closest to that date from the CurrencyRate table. If an exact match exists in the database for the datetime field, it should be returned; if not, select the record with the smallest time difference, regardless of whether it is earlier or later than the requested moment.

class CurrencyRate(models.Model):
    rate = models.DecimalField(...)
    datetime = models.DateTimeField(...)
+--------+----------------------------+
| rate   | datetime                   |
+--------+----------------------------+
| 34.9   | 1999-05-21 15:44:12.983411 |
| 70.3   | 2022-12-20 08:30:16.123351 |
| 68.1   | 2023-01-09 10:13:30.431559 |
| 68.2   | 2023-01-10 10:00:12.123471 |
+--------+----------------------------+
import datetime as dt

def index(request):
    my_dt: dt.datetime = get_dt_from_request(request)
    ...
Determining the nearest exchange rate for the… - sobes.tech