Sobes.tech
Junior — Senior

Finding the currency exchange rate closest to the specified date

livecode

Task condition

It is necessary to implement a function that, given a date, returns the currency exchange rate recorded in the database at the time closest to that date. An example uses the Django model CurrencyRate, which contains fields rate (Decimal) and datetime (DateTime). The table may have records from different years, and the query should select the value whose timestamp deviates minimally from the requested date.

# currency service
class CurrencyRate(models.Model):
    rate = models.DecimalField(...)
    datetime = models.DatetimeField(...)

# Example table data
| 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 12:30:13.431559    |
| 68.2 | 2023-01-10 10:00:12.123471    |

# Example conversions
| 2020-12-20 00:00:00.000000 -> 70.3 |
| 2000-12-20 00:00:00.000000 -> 34.9 |

def handler(dt: datetime) -> Decimal:
    ...