如何将日期值映射到 Python 中的时间戳范围?
How to map a date value to a timestamp range in Python?
我 using an API 将日期范围作为有效负载的一部分。使用 2 个日期时间参数指定范围,指示范围的开始和结束:
| 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 |
调用此 API 时,我想使用一周的固定子时间间隔:since
为周五晚上 8 点,until
为周一上午 8 点。我目前正在使用这样的特定日期范围对其进行测试:
payload = {
'since': '2020-03-27T20:00-05',
'until': '2019-03-30T08:00-05'
}
在我的脚本中,我想给出一个日期作为输入,并将该日期映射到一个负载,该负载为该日期的最近时间实例指定 since
和 until
间隔。我不知道该怎么做,你能帮忙吗?
如果我对你的问题的理解正确,你希望能够获取任何随机日期并将其转换为周五晚上 8 点到周一早上 8 点的日期范围?
你可以这样做:
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'])
将输出:
2020-04-03T20:00:00 2020-04-06T08:00:00
它以ISO格式的日期作为输入,并将其调整为最后一个星期五-星期一的日历时间段。如果这不是您想要的,您可以调整 monday
和 friday
以给出不同的日期,但这给出了基本的想法。
我 using an API 将日期范围作为有效负载的一部分。使用 2 个日期时间参数指定范围,指示范围的开始和结束:
| 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 |
调用此 API 时,我想使用一周的固定子时间间隔:since
为周五晚上 8 点,until
为周一上午 8 点。我目前正在使用这样的特定日期范围对其进行测试:
payload = {
'since': '2020-03-27T20:00-05',
'until': '2019-03-30T08:00-05'
}
在我的脚本中,我想给出一个日期作为输入,并将该日期映射到一个负载,该负载为该日期的最近时间实例指定 since
和 until
间隔。我不知道该怎么做,你能帮忙吗?
如果我对你的问题的理解正确,你希望能够获取任何随机日期并将其转换为周五晚上 8 点到周一早上 8 点的日期范围?
你可以这样做:
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'])
将输出:
2020-04-03T20:00:00 2020-04-06T08:00:00
它以ISO格式的日期作为输入,并将其调整为最后一个星期五-星期一的日历时间段。如果这不是您想要的,您可以调整 monday
和 friday
以给出不同的日期,但这给出了基本的想法。