How can we loop through dates in a dataframe, and append strings to create a valid URL?

Question:

I am trying to loop through dates in a dataframe (dates are formatted as string type) and get two rows at a time, for start and end. For each pair, I am trying to append to a string to create a URL and pass it to an API. Here is the code that I have so far.

import pandas as pd
from datetime import date, timedelta

sdate = date(2023,1,1)   # start date
edate = date(2023,3,20)  # end date

df_dates=pd.date_range(sdate,edate-timedelta(days=1),freq='w')
df_dates=pd.DataFrame(df_dates)
print(type(df_dates))
print(df_dates.shape)
df_dates.columns = ['mydate']
df_dates['mydate']=df_dates['mydate'].astype(str)
print(df_dates.dtypes)
df_dates

The above part seems pretty much OK, unless I am missing something. Then, I run this line of code.

url = "https://internal_api/assets?StartTime="+ str(row1) +"T12:00:12-04:00&EndTime="+ str(row2) +"T12:00:12-04:00"

Now, when I print the URL, I get this.

https://internal_api/assets?StartTime=mydate    2023-03-12
Name: 10, dtype: objectT12:00:12-04:00&EndTime=mydate    2023-03-19
Name: 11, dtype: objectT12:00:12-04:00

This is what I actually need.

"https://internal_api/assets?startTime=2023-03-12T14%3A00%3A12-04%3A00&endTime=2023-03-19T14%3A00%3A12-04%3A00"

How can I change the first URL into the second URL?

Asked By: ASH

||

Answers:

If I understand you correctly you can use zip():

url = "https://internal_api/assets?StartTime={date1}T12:00:12-04:00&EndTime={date2}T12:00:12-04:00"

for date1, date2 in zip(df_dates['mydate'][::2], df_dates['mydate'][1::2]):
    print(url.format(date1=date1, date2=date2))

Prints:

https://internal_api/assets?StartTime=2023-01-01T12:00:12-04:00&EndTime=2023-01-08T12:00:12-04:00
https://internal_api/assets?StartTime=2023-01-15T12:00:12-04:00&EndTime=2023-01-22T12:00:12-04:00
https://internal_api/assets?StartTime=2023-01-29T12:00:12-04:00&EndTime=2023-02-05T12:00:12-04:00
https://internal_api/assets?StartTime=2023-02-12T12:00:12-04:00&EndTime=2023-02-19T12:00:12-04:00
https://internal_api/assets?StartTime=2023-02-26T12:00:12-04:00&EndTime=2023-03-05T12:00:12-04:00
https://internal_api/assets?StartTime=2023-03-12T12:00:12-04:00&EndTime=2023-03-19T12:00:12-04:00
Answered By: Andrej Kesely