0

重复调用最后带有时间戳的 Web URL,示例 URL ' https://mywebApi/StartTime=2019-05-01%2000:00:00&&endTime=2019-05-01%2003:59:59 '

StartTime=2019-05-01%2000:00:00 是时间 2019-05-01 00:00:00 的 URL 表示

endTime=2019-05-01%2003:59:59 是时间 2019-05-01 00:00:00 的 URL 表示

要求是重复呼叫,有 4 小时的窗口。在增加 4 小时时,日期可能会发生变化,是否有一种精简的方式来生成 URL 字符串,比如

baseUrl = 'https://mywebApi/StartTime='
startTime = DateTime(2018-05-03 00:01:00)
terminationTime = DateTime(2019-05-03 00:05:00)
while (startTime < terminationTime):
    endTime = startTime + hours(4)
    url = baseUrl+str(startTime)+"endtime="+str(startTime)
    # request get url
    startTime = startTime + hours(1)
4

1 回答 1

1

You can use Datetime.timedelta as well as the strftime function as follows:

from datetime import datetime, timedelta
baseUrl = 'https://mywebApi/StartTime='
startTime = datetime(year=2018, month=5, day=3, hour=0, minute=1, second=0)
terminationTime = datetime(year=2018, month=5, day=3, hour=3, minute=59, second=59)
while (startTime < terminationTime):
    endTime = startTime + timedelta(hours=4)
    url = baseUrl + startTime.strftime("%Y-%m-%d%20%H:%M:%S") + "endtime=" + endtime.strftime("%Y-%m-%d%20%H:%M:%S")
    # request get url
    startTime = endTime

The following link is useful https://www.guru99.com/date-time-and-datetime-classes-in-python.html or you can look at the official datetime documentation.

edit: using what u/John Gordan said to declare the initial dates

于 2019-07-10T20:12:17.957 回答