简体   繁体   中英

How to pass a currentday() type date/datetime function as a filter to an API in python?

I need to download current day minus 1 data from https://retsapi.raprets.com/CIN/RESO/OData/ every day by passing a filter condition like "&$filter=ModificationTimestamp%20ge%20%272022-03-04T13%3A19%3A56Z%27". Instead of passing timestamp value like I did in the filter condition mentioned I want to pass a date/datetime function. I am using python to make get calls to the API.

How do I make the below code work?

import requests  
import json

from datetime import datetime

bearerAccessToken = '#####################'

now = datetime.now()

resourceUrl = "https://retsapi.raprets.com/CIN/RESO/OData/Property?Class=Residential&$filter=ModificationTimestamp{}".format(now)

r = requests.get(resourceUrl, headers={'Authorization' : 'Bearer '+ bearerAccessToken})

print(r.text)

Above code is failing with syntax error:

"error":{ "code":"","message":"An error has occurred.","innererror":{ "message":"Syntax error at position 28 in 'ModificationTimestamp2022-08-01 15:58:03.154348'.","type":"Microsoft.OData.Core.ODataException","stacktrace":"

The correct syntax is "ModificationTimestamp%20ge%20%272022-03-04T13%3A19%3A56Z%27".

How do I convert the output of datetime.now() to match "%20ge%20%272022-03-04T13%3A19%3A56Z%27"?

Assuming you mean you want to pass the output of a date function, you could just use .format() to create the url string and pass the function in there.

def a_date_function():
    # code converting string values to appropiate ascii chars
    return desired_output

url = "https://retsapi.raprets.com/CIN/RESO/OData/&$filter=ModificationTimestamp{}".format(a_date_function())

api_output = requests.get(url)

And that should give you a full url string with the output from the date function tacked on to the end where the {} is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM