如何将dt.datetime转换为用于以下api调用的isoformat



我必须以以下方式调用api:

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'))

我必须使用变量start和end作为时间戳_gte和时间戳_lte的输入。起始变量的格式如下:datetime.datetime(2022,1,1,0,0(。

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

我正在使用以下方法将其转换为iso格式:

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

我将iso格式转换后的开始和结束放在我的api调用中,但我仍然得到<响应[500]>。

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

可能是因为时间戳_gte=2022-01-01T00:00:00Z是必需的输入,而不是"2022-01-01D00:00:00Z'"。如何将开始和结束变量转换为所需的格式,以确保我的api调用正常工作?

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

通过此行,您可以传递'start'作为参数,而不是start变量的值。

一种方法是用f-string构造URL:

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

然而,正如我所说,你应该使用

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'))

检查文档

请注意,这不会讨论startend日期时间对象的潜在时区问题,这些问题可能会影响实际和预期的API响应。

您可能需要转换到服务器时区

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'))

请重新检查您的要求

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

最新更新