如何在Python中将日期值映射到时间戳范围?

问题描述 投票:0回答:1

我是using an API,它将日期范围作为有效载荷的一部分。使用2个datetime参数指定范围,该参数指示范围的开始和结束:

| 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'
}

在我的脚本中,我想提供一个日期作为输入,并将该日期映射到指定该时间间隔的最新时间实例的sinceuntil的有效负载。我不确定该怎么做,您能帮忙吗?

python python-3.x date date-range
1个回答
2
投票

如果我正确理解了您的问题,您希望能够获取任何随机日期并将其转换为周五8PM到周一8AM的日期范围?

您可以这样做:

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格式的日期作为输入,并将其调整为最后一个星期五至星期一的日历时段。如果不是您想要的,您可以调整mondayfriday来指定不同的日期,但这给出了基本的思想。

© www.soinside.com 2019 - 2024. All rights reserved.