【问题标题】:using python convert UTC time to local time of Longitude and latitude provided使用python将UTC时间转换为提供的经纬度本地时间
【发布时间】:2017-07-31 05:54:13
【问题描述】:

我正在使用日出日落 api 来获取当天的日出和日落。

>>> url = "https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400&date=2017-07-31"
>>> import urllib2
>>> import json
>>> resp = urllib2.urlopen(url)
>>> data = json.load(resp)
>>> sunriseUtc = data.get("results").get("sunrise")
>>> sunriseUtc
u'5:23:18 AM'

我想将此 UTC 时间转换为在 URL 中传递的 Long、Lat 的本地时间。即不是本地用户。

任何帮助将不胜感激。

【问题讨论】:

  • @Rahul 我不想转换为本地日期时间
  • 您是指“当地时间”还是“天文时间”?因为和当地时间不一样,比如华沙的当地时间和巴黎的时间是一样的,尽管天文时间相差很大……
  • 这不是那个的副本。难题是根据经度和纬度确定您所在的国家/地区,然后确定该国家/地区的 UTC 偏移量,然后在给定 UTC 偏移量的情况下以这些经纬度坐标生成本地时间。

标签: python datetime utc timezone-offset


【解决方案1】:

您最好使用 pyephem,而不是使用网络查询,它是 pip install pyephem 能够为您提供给定位置(纬度/经度)的日出/日落时间(以及更多时间) ,基于物理值。

>>> import ephem
>>> sun = ephem.Sun()
>>> greenwich = ephem.Observer()
>>> greenwich.lat = '51:28:38'
>>> print(greenwich.horizon)
0:00:00.0
>>> greenwich.date = '2007/10/1'
>>> r1 = greenwich.next_rising(sun)
>>> greenwich.pressure = 0
>>> greenwich.horizon = '-0:34'
>>> greenwich.date = '2007/10/1'
>>> r2 = greenwich.next_rising(sun)
>>> print('Visual sunrise: %s' % r1)
Visual sunrise: 2007/10/1 05:59:30
>>> print('Naval Observatory sunrise: %s' % r2)
Naval Observatory sunrise: 2007/10/1 05:59:50

【讨论】:

  • 好吧,我会试一试,但我更喜欢准确性
  • 我想你会发现如果正确使用pyephem的准确率是非常高的。此外,它当然可以离线工作。
  • 它还具有UTC和观察者位置时间之间的转换。
【解决方案2】:

使用 Python 3.8:

开始添加以下模块:

进口时间

从时间导入本地时间

接下来,调用 localtime() 方法并插入您的时间(在本例中为变量“sunriseUtc”):

当地时间(sunriseUtc)。

就是这样。

如果您想格式化时间(如何呈现),您需要从时间模块导入 strftime(字符串格式时间的缩写)。然后为您的时间设置格式。然后从上面传递相同的参数: 例如

从时间导入 strftime

strftime("%m/%d/%Y %I:%M:%S %p", localtime(sunriseUtc))

'05/12/2019 05:57:05 AM'

当我使用 requests 模块从 openweathermap.org 的 API 下载数据时,这对我有用。

如果您需要更多支持,请参阅时间模块的文档: https://docs.python.org/2/library/time.html#time.strftime

注意:我的项目是基于此处的“项目:获取当前天气数据”示例构建的: https://automatetheboringstuff.com/chapter14/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-27
    • 2023-03-31
    • 2018-10-30
    • 2014-07-18
    • 2021-02-04
    • 2010-09-15
    • 2011-05-01
    相关资源
    最近更新 更多