Home > Blockchain >  How to convert dt.datetime into isoformat to use in the following api call?
How to convert dt.datetime into isoformat to use in the following api call?

Time:01-30

I have to call api in the following manner:

import requests
from requests.auth import HTTPBasicAuth
response= requests.get("https://api.com/?device_id=1&timestamp__gte=2021-09-01T18:30:00Z&timestamp__lte=2021-09-02T18:30:00Z",auth = HTTPBasicAuth('user', 'password'))

I have to use variables start and end as input for timestamp__gte and timestamp__lte. The start variable is in the following format: datetime.datetime(2022, 1, 1, 0, 0).

print(start)
#->datetime.datetime(2022, 1, 1, 0, 0)

I am using the following method to convert this to iso format:

start=start.isoformat()
start= start 'Z'
print(start)
#->'2022-01-01T00:00:00Z'

I am putting the iso format converted start and end in my api call but I am still getting <Response[500]>.

response = requests.get("https://api.com/?device_id=1&timestamp__gte=start&timestamp__lte=end",auth = HTTPBasicAuth('user', 'password'))
print(response)
#-> <Response[500]>

Probably because timestamp__gte= 2022-01-01T00:00:00Z is the required input instead of '2022-01-01T00:00:00Z'. How do I convert start and end variables to the desired format to ensure that my api call works?

CodePudding user response:

response= requests.get("https://api.com/?device_id=1&timestamp__gte=start&timestamp__lte=end",auth = HTTPBasicAuth('user', 'password'))

With this line you pass 'start' as parameter, not the value of start variable.

One way is to construct the URL with f-string:

url = f"https://api.com/?device_id=1&timestamp__gte={start}&timestamp__lte={end}"
response = requests.get(url, auth=HTTPBasicAuth('user', 'password'))

However, as I said you should be using

base_url = 'https://api.com/'
payload = {'device_id':1,
           'timestamp__gte':start,
           'timestamp__lte':end}
response = requests.get(base_url, data=payload, auth=HTTPBasicAuth('user', 'password'))

check the docs

Note, this does not discuss potential time-zone issues with your start and end datetime objects that may affect the actual vs expected API response.

CodePudding user response:

probably you need to convert to the server timezone

from datetime import datetime, timedelta, timezone
from tzlocal import get_localzone

local_tz = get_localzone()
timestamp = '1643533570'
local_datetime = datetime.fromtimestamp(timestamp).astimezone(local_tz)

datestring = "2022-01-30 00:00:00"
utc_datetime = datetime.fromisoformat(datestring).astimezone(timezone.utc)
local_datetime = datetime.fromtimestamp(datestring).astimezone(local_tz)
print(utc_time.isoformat(timespec='seconds'))

please recheck on your request

requests.get(url=url, headers={'user': username, 'password': password}, data={'start':'datestring', 'end':'datestring2'})
  •  Tags:  
  • Related