user2458922
user2458922

Reputation: 1721

Python Generating Date Time as Sting with time increments to generate URL

To Repeatedly call a web URL which has time stamp in the end, Example URL 'https://mywebApi/StartTime=2019-05-01%2000:00:00&&endTime=2019-05-01%2003:59:59'

StartTime=2019-05-01%2000:00:00 is URL representation of Time 2019-05-01 00:00:00

endTime=2019-05-01%2003:59:59 is URL representation of Time 2019-05-01 00:00:00

Requirement is to make repetitive calls , with 4 hour window. While adding 4 hours, the date may change, Is there a lean way to generate the URL String, Some thing like

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)

Upvotes: 0

Views: 88

Answers (1)

PoorProgrammer
PoorProgrammer

Reputation: 497

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

Upvotes: 1

Related Questions