Reputation: 87
I am using an API that takes a date range as part of the payload. The range is specified using 2 datetime parameters indicating the beginning and end of the range:
| Name | Type | Description | Format | Required |
|-------+--------+------------------------------------------------------------+---------------------+-------------|
| since | string | The start of the date range over which you want to search. | format: "date-time" | optional |
| | | | | |
| until | string | The end of the date range over which you want to search. | format: "date-time" | optional |
When calling this API I want to use a fixed subinterval of the week: since
as Friday at 8PM, and until
as Monday at 8AM. I'm currently testing it with a specific date range like this:
payload = {
'since': '2020-03-27T20:00-05',
'until': '2019-03-30T08:00-05'
}
In my script, I want to give a single date as the input, and have that date mapped to a payload that specifies the since
and until
for the most recent temporal instance of that interval. I am not sure how to do that, can you help?
Upvotes: 0
Views: 2238
Reputation: 7978
If I am understanding your question correctly, you want to be able to take any random date and translate that into a date range Fri 8PM to Mon 8AM?
You can do this:
import datetime
def make_payload(date_str):
today = datetime.date.fromisoformat(date_str)
monday = datetime.datetime.fromisoformat(
str(datetime.date.fromordinal(
(today.toordinal() - today.toordinal() % 7) + 1)) + " 08:00")
friday = datetime.datetime.fromisoformat(
str(datetime.date.fromordinal(
(today.toordinal() - today.toordinal() % 7) - 2)) + " 20:00")
payload = {'since': friday.isoformat(),
'until': monday.isoformat()}
return payload
payload = make_payload('2020-04-07')
print(payload['since'], payload['until'])
that will output:
2020-04-03T20:00:00 2020-04-06T08:00:00
it takes a date in ISO format as input, and adjusts it to the last Friday-Monday calendar period. You can tweak monday
and friday
to give different days if that's not quite what you want, but this gives the basic idea.
Upvotes: 2