時區。如果我運行這個網址:https://api.sunrise-sunset.org/json?lat=12.98&lng=77.61&date=2017-08-26得到不正確的UTC爲本地時間時給出
我得到日出時間:「上午12時38分十四秒」 ,這是UTC時間,如果我把它轉換成使用給定的時區:
from datetime import datetime
import pytz
from dateutil import tz
def convertUTCtoLocal(date, utcTime, timezone):
""" converts UTC time to given timezone
"""
to_zone = pytz.timezone(timezone)
from_zone = _tz.gettz('UTC')
utc = _datetime.strptime('%s %s' % (date, utcTime), '%Y-%m-%d %H:%M:%S')
utc = utc.replace(tzinfo=from_zone)
local = utc.astimezone(to_zone)
return str(local.time())
但這返回18:08:16
這是晚上時間,所以我在做什麼錯在這裏。
給出timzone是Asia/Kolkata
例子:
>>> from datetime import datetime
>>> from dateutil import tz
>>> from_zone = tz.gettz('UTC')
>>> to_zone = tz.gettz('Asia/Kolkata')
>>> utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')
>>> utcTime = "12:38:16" ## from json URL we get AM/PM but I remove it.
>>> utc = datetime.strptime('2017-08-26 {}'.format(utcTime), '%Y-%m-%d %H:%M:%S')
>>> utc
datetime.datetime(2017, 8, 26, 12, 38, 16)
>>> utc = utc.replace(tzinfo=from_zone)
>>> central = utc.astimezone(to_zone)
>>> central
datetime.datetime(2017, 8, 26, 18, 8, 16, tzinfo=tzfile('/usr/share/zoneinfo/Asia/Kolkata'))
你可以舉例和日期,utcTime和時區? – ands
@ands:對不起,我已經更新它。 –
謝謝,我弄明白了,請爲函數convertUTCtoLocal的參數添加一組示例。 – ands