当我从timezonedb(python)查询时间时,为什么会得到错误的输出时间

2024-10-04 11:31:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个时区(fromtz)中给出日期(indate,inmonth)和时间(intime),然后使用timezonedbapi请求另一个时区(totz)中的时间

indate = args[0]
inmonth=args[1]
intime=args[2]
fromtz=args[3]
totz=args[4]

inyear = datetime.now().year

print(str(indate)+'/'+str(inmonth)+'/'+str(inyear)+' '+str(intime))
dt_obj = datetime.strptime(str(indate)+'/'+str(inmonth)+'/'+str(inyear)+' '+str(intime),'%d/%m/%Y %H:%M')

millisec = dt_obj.timestamp() * 1000
url="http://api.timezonedb.com/v2.1/convert-time-zone?key="+API_KEY+"&format=json&from="+fromtz+"&to="+totz+"&time="+str(int(millisec))

response = requests.get(url)
jsonoutput = json.loads(response.text)
timeoutputms = jsonoutput["toTimestamp"]
outputdt = datetime.fromtimestamp(timeoutputms/1000).strftime('%d/%m %H:%M')

测试1:

Input - 30 01 00:00 CST GMT

Output - 30/01 00:00 CST

Correct output must be - 30/01 06:00 CST

测试2:

Input - 30 01 00:00 GMT CST

Output - 29/01 23:59 CST

Correct output must be - 29/01 18:00 CST

JSON响应:{'status':'OK','message':'''fromZoneName':'Europe/Jersey','From缩写':'GMT','fromTimestamp':1611945000000,'toZoneName':'America/North_Dakota/Beulah','ToabRevision':'CST','toTimestamp':1611944978400,'offset':-21600}


Tags: objdatetime时间dtargsgmtstrcst
1条回答
网友
1楼 · 发布于 2024-10-04 11:31:29

如果使用正确的时区名称(如timezonedb docs中所列),您的查询原则上是有效的。明确的缩写词,如GMT或UTC也应适用

Ex:

import requests
import json
from datetime import datetime
from dateutil.tz import gettz

myZone, toZone = "Europe/London", "America/New_York"

# localize to my tz, set microsecs zero
now = datetime.now(gettz(myZone)).replace(microsecond=0)
msec = now.timestamp()*1000

# now query timezonedb
url = f"http://api.timezonedb.com/v2.1/convert-time-zone?key={API_Key}&format=json&from={myZone}&to={toZone}&time={int(msec)}"
response = requests.get(url)
jsonoutput = json.loads(response.text)
timeoutputms = jsonoutput["toTimestamp"]

# ...and convert back to Python datetime for sanity-check
now_toZone = datetime.fromtimestamp(timeoutputms/1000, gettz(toZone))

print(f"input: {now}\noutput: {now_toZone}\ndiff: {(now_toZone-now).total_seconds()} s")
# input: 2021-02-02 14:37:02+00:00
# output: 2021-02-02 09:36:44-05:00
# diff: -18.0 s

有趣的是,对于我的测试查询,输入和输出被关闭了约18秒。我不知道这是从哪里来的,但这是离题的

相关问题 更多 >