2017-08-26 50 views
0

時區。如果我運行這個網址: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')) 
+0

你可以舉例和日期,utcTime和時區? – ands

+0

@ands:對不起,我已經更新它。 –

+0

謝謝,我弄明白了,請爲函數convertUTCtoLocal的參數添加一組示例。 – ands

回答

0

的問題是,你有 「上午12點38分16秒」,這是真正的 「零時38分16秒」 這樣你就可以'只是去掉「AM」。我改變了你的功能,所以它會用「AM」和「PM」小時的工作,只是不剝離「AM」和「PM」使用功能前:

import pytz 
from _datetime import datetime 
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') 
    ## for formating with AM and PM hours in strptime you need to add 
    ## %p at the end, also instead of %H you need to use %I 
    utc = datetime.strptime('%s %s' % (date, utcTime), '%Y-%m-%d %I:%M:%S %p') 
    utc = utc.replace(tzinfo=from_zone) 
    local = utc.astimezone(to_zone) 
    return str(local.time()) 


date = '2017-08-26' 
utcTime = '12:38:14 AM' ## Don't strip AM or PM 
timezone = 'Asia/Kolkata' 
x = convertUTCtoLocal(date, utcTime, timezone) 
print(x) 

此外,你可以看到工作示例here

+0

非常感謝(y) –