得到不正确的UTC为本地时间时给出
问题描述:
时区。如果我运行这个网址: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'))
答
的问题是,你有 “上午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) –
你可以举例和日期,utcTime和时区? – ands
@ands:对不起,我已经更新它。 –
谢谢,我弄明白了,请为函数convertUTCtoLocal的参数添加一组示例。 – ands