如何根据日期在URL中传递开始日期和结束日期?

时间:2019-05-22 15:58:19

标签: python python-3.x

我正在尝试在URL中添加开始日期和结束日期。如何基于一天在URL中传递start_date :2017-11-11End_date: 2017-11-14

我写了一些代码,能够获得日期之间的天数列表,并能够打印开始日期和结束日期之间的日期。但是当我在URL中传递日期时,只用了一天,我需要如下结果:

import datetime
from datetime import timedelta

dateformat = '%Y-%m-%d'
startdate = datetime.datetime.strptime('2017-11-11', dateformat)
enddate = datetime.datetime.strptime('2017-11-13', dateformat)
date_array = \
  (startdate + datetime.timedelta(days=x) for x in range(0, (enddate-startdate).days + 1))
print("Number of days", (enddate-startdate).days)

for date_object in date_array:
    print("List of date", date_object.strftime(dateformat))

nextday = (startdate + datetime.timedelta(days=1))
print( "Next day", nextday.strftime(dateformat))

link = 'https://xyx?start_date='+ startdate.strftime(dateformat) + '&end_date=' + nextday.strftime(dateformat)
print("print link", link)

当前代码的输出:

Number of days 2
List of date 2017-11-11
List of date 2017-11-12
List of date 2017-11-13
Next day 2017-11-12
print link https://xyx?start_date=2017-11-11&end_date=2017-11-12

预期输出:

Number of days 2
List of date 2017-11-11
List of date 2017-11-12
List of date 2017-11-13
Next day 2017-11-12
print link https://xyx?start_date=2017-11-11&end_date=2017-11-12
print link https://xyx?start_date=2017-11-12&end_date=2017-11-13

1 个答案:

答案 0 :(得分:1)

看看:

import datetime
from datetime import timedelta

dateformat = '%Y-%m-%d'
startdate = datetime.datetime.strptime('2017-11-11', dateformat)
enddate = datetime.datetime.strptime('2017-11-13', dateformat)
date_array = [startdate + datetime.timedelta(days=x) for x in range(0, (enddate - startdate).days + 1)]
print("Number of days", (enddate - startdate).days)
for date_object in date_array:
    print("List of date", date_object.strftime(dateformat))

nextday = (startdate + datetime.timedelta(days=1))
print("Next day", nextday.strftime(dateformat))

link = 'https://xyx?start_date=' + startdate.strftime(dateformat) + '&end_date=' + nextday.strftime(dateformat)
print("print link", link)
print("*"*20)
for i in range(len(date_array)):
    if i + 1 < len(date_array):
        link = 'https://xyx?start_date=' + date_array[i].strftime(dateformat) + '&end_date=' + date_array[i+1].strftime(dateformat)
        print (link)

输出为:

Number of days 2
List of date 2017-11-11
List of date 2017-11-12
List of date 2017-11-13
Next day 2017-11-12
print link https://xyx?start_date=2017-11-11&end_date=2017-11-12
********************
https://xyx?start_date=2017-11-11&end_date=2017-11-12
https://xyx?start_date=2017-11-12&end_date=2017-11-13