简体   繁体   中英

using python convert UTC time to local time of Longitude and latitude provided

I am using sunrise-sunset api to get sunrise and sunset for day.

>>> 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'

I want to convert this UTC time to local time of that of Long, Lat passed in the URL. ie not user local.

Any help would be greatly appreciated.

Rather than using a web query you might be better off using pyephem, it is pip install pyephem able and will give you the sunrise/set times, (and a lot more), for a given location, (lat/long), based on physical values.

>>> 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

Using Python 3.8:

To Begin add the following modules below:

import time

from time import localtime

Next, call on the localtime() method and insert your time (in this case, variable "sunriseUtc"):

localtime(sunriseUtc).

That's it.

If you would like to format the time (how it is presented) you will need to import strftime (abbreviated for string format time) from the time module. Then set up the format for your time. Then pass the same argument from above: eg

from time import strftime

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

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

This worked for me when using the requests module to download data from the openweathermap.org's API.

If you need more support, see time module's documentation: https://docs.python.org/2/library/time.html#time.strftime

Note: My project was built on the example from "Project: Fetching Current Weather Data" found here: https://automatetheboringstuff.com/chapter14/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM