Reputation: 143
I'm trying to get my home automation project to switch a light on at sunset. I'm using this code to get sunset from my location:
import requests
import json
url = "http://api.sunrise-sunset.org/json?lat=xx.xxxxxx&lng=-x.xxxxx"
response = requests.request("GET", url)
data=response.json()
print(json.dumps(data, indent=4, sort_keys=True))
This returns:
{
"results": {
"astronomical_twilight_begin": "5:46:47 AM",
"astronomical_twilight_end": "6:02:36 PM",
"civil_twilight_begin": "7:08:37 AM",
"civil_twilight_end": "4:40:45 PM",
"day_length": "08:15:09",
"nautical_twilight_begin": "6:26:43 AM",
"nautical_twilight_end": "5:22:39 PM",
"solar_noon": "11:54:41 AM",
"sunrise": "7:47:07 AM",
"sunset": "4:02:16 PM"
},
"status": "OK"
}
I'm only just starting to get my head round JSON so my questions are:
What I'm trying to do is:
Get the time now
Get sunset time
If time.now > sunset
switch light on
I've got about 5 hours to find the answer or I'll have to wait 24 hours to test it :)
Upvotes: 0
Views: 183
Reputation: 364
Heres is your complete code:
import requests
import datetime
import json
url = "https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400"
response = requests.request("GET", url)
data=response.json() #Getting JSON Data
sunset_time_str=data['results']['sunset'] #Getting the Sunset Time
current_date=datetime.date.today() #Getting Today Date
sunset_time=datetime.datetime.strptime(sunset_time_str,'%I:%M:%S %p') #Converting String time to datetime object so that we can compare it current time
sunset_date_time=datetime.datetime.combine(current_date,sunset_time.time()) #Combine today date and time to single object
current_date_time=datetime.datetime.now()
if current_date_time > sunset_date_time:
print('Turn On light')
else:
print('Dont Turn ON')
Upvotes: 1
Reputation: 8646
You need time
module and strptime
function to parse the value. I let you study format specification by yourself with following url:
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
This example parses your time and outputs it.
import time
import datetime
data = {
"results": {
"astronomical_twilight_begin": "5:46:47 AM",
"astronomical_twilight_end": "6:02:36 PM",
"civil_twilight_begin": "7:08:37 AM",
"civil_twilight_end": "4:40:45 PM",
"day_length": "08:15:09",
"nautical_twilight_begin": "6:26:43 AM",
"nautical_twilight_end": "5:22:39 PM",
"solar_noon": "11:54:41 AM",
"sunrise": "7:47:07 AM",
"sunset": "4:02:16 PM"
},
"status": "OK"
}
t = time.strptime(data['results']['sunset'], '%I:%M:%S %p')
sunset = datetime.datetime.fromtimestamp(time.mktime(t)).time()
now = datetime.datetime.now().time()
print('Now: {}, Sunset: {}'.format(now, sunset))
if now < sunset:
print('Wait man...')
else:
print('Turn it ON!')
Upvotes: 1