Return sunrise and sunset time based on a datetime using Python

时间:2019-03-19 14:41:30

标签: python pandas datetime timezone

My df is like this.

DateTime            Pdc
01/04/2016 10:00    1
01/04/2016 10:05    2
02/04/2016 10:10    3
02/04/2016 10:15    4
03/04/2016 10:20    5
03/04/2016 10:25    6
03/04/2016 10:30    7

I want to add two columns of sunrise time and sunset time based on the date on the df like below as an example:

DateTime            Pdc  Sunrise  Sunset
01/04/2016 10:00    1    time     time
01/04/2016 10:05    2    time     time
02/04/2016 10:10    3    time     time
02/04/2016 10:15    4    time     time
03/04/2016 10:20    5    time     time
03/04/2016 10:25    6    time     time
03/04/2016 10:30    7    time     time

I have no idea how to do that. Trying this, I don't know how to implement it without package timezone. This return error that I cannot solve. This works with Python 2, I didn't check it. This works for cities on the list, but not my cities.

1 个答案:

答案 0 :(得分:0)

您可以从https://sunrise-sunset.org/api检索日落和日出时间。 您所需要做的就是了解您的纬度和经度。如果您不认识它们,则可以从geopy lib中获取它们:

import requests
from geopy.geocoders import Nominatim

location = Nominatim().geocode('Moscow')
r = requests.get('https://api.sunrise-sunset.org/json', params={'lat': location.latitude, 'lng': location.longitude}).json()['results']
print('Sunrise:', r['sunrise'])
print('Sunset:', r['sunset'])

输出:

Sunrise: 3:30:56 AM
Sunset: 3:42:58 PM