使用pytz将UTC转为日本当地时间但代码仍输出UTC的问题求解
问题原因
- 仅完成了
f变量的时区转换逻辑,Circumpolar分支下的sun变量直接调用iso属性输出,astropy的Time对象默认输出UTC时间,未做时区转换 - 非Circumpolar、非AlwaysBelowTheHorizon分支下的
sun变量始终为浮点数格式的儒略日,未统一转换为带时区信息的时间对象,容易因findIntersection的内部逻辑导致时区信息丢失
修复方案
首先导入正确的时区依赖,Python3.9及以上版本使用内置zoneinfo:
from zoneinfo import ZoneInfo # 低版本Python使用pytz的话替换为:from pytz import timezone # 后续所有ZoneInfo("Asia/Tokyo")对应替换为timezone("Asia/Tokyo")
- 修正Circumpolar分支的
sun时间转换逻辑:
elif Circumpolar: sun = Time(sun, format='jd') # 统一转换为日本时区时间 sun_jst = [t.to_datetime(ZoneInfo("UTC")).astimezone(ZoneInfo("Asia/Tokyo")) for t in sun] if night_time: post_message_to_slack("Bingo! We can observe it now until sunrise at {}".format(sun_jst[1])) else: post_message_to_slack("Sun will set at {}".format(sun_jst[0]))
- 修正
f变量的转换逻辑,避免隐式类型转换丢失时区:
f = findIntersection(intervals, N) # 显式完成UTC转日本时区的流程 f_utc = [Time(t, format='jd').to_datetime(ZoneInfo("UTC")) for t in f] f_jst = [t.astimezone(ZoneInfo("Asia/Tokyo")) for t in f_utc] # 若需要格式化输出可使用strftime,例:f_jst[0].strftime("%Y-%m-%d %H:%M:%S") post_message_to_slack("We can observe it from {} to {}".format(f_jst[0], f_jst[1]))
内容的提问来源于stack exchange,提问作者madgoat
相关产品推荐
相关产品推荐

