【问题标题】:Why do i get wrong output time when I query time from timezonedb (python)当我从 timezonedb (python) 查询时间时,为什么我得到错误的输出时间
【发布时间】:2021-05-06 16:16:04
【问题描述】:

我正在尝试从一个时区(fromtz)给出日期(indate,inmonth)和时间(intime),然后使用 timezonedb api 请求另一个时区(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:

输入 - 30 01 00:00 CST GMT

输出 - 30/01 00:00 CST

正确的输出必须是 - 30/01 06:00 CST

测试 2:

输入 - 30 01 00:00 GMT CST

输出 - 29/01 23:59 CST

正确的输出必须是 - 29/01 18:00 CST

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

【问题讨论】:

标签: python datetime timezone timezonedb


【解决方案1】:

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

例如:

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 秒。不知道这是从哪里来的,但这里离题了。

【讨论】:

  • 我正在尝试做类似的事情。通常,新的发布公告是以 EST 等时区代码发布的,我希望将其转换为该人的本地时区。很多人不知道时区属于哪个国家,我也检查了 EST 到 IST 但它不起作用。
  • @DeadPool:如果你在你的问题下考虑我的评论,如果你只有有缩写的 tz 名字,在很多情况下,你只需要猜测 i> 实际时区。不是你作为程序员通常想要的那种方法;-)
  • 但是像 savvytime 这样的网站如何转换时间.. 我想要一种转换时区的方法,而不是每次都去网站。他们已经正确处理了从 est 到 GMT 的转换。
  • @DeadPool:some 缩写是明确的,如果需要本地时间,还有你的 IP 地址。如果您只需要在 Python 中转换 tz,您有很多选择,请参阅包 zoneinfo、dateutil、pytz 等。
猜你喜欢
  • 2012-12-27
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2021-11-11
  • 2018-12-21
  • 2020-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多