Python Camera Adjust Iso For Sunset And Sunrise

Install the `astral` Python package.

sudo pip install astral

Be sure to [set the timezone].

Python script to adjust the iso based on sunrise and sunset.

#get access to the camera
from picamera import PiCamera

#import so we can invoke another script
import subprocess

#get access to the clock
import datetime

#sleep so we can wait on the camera
from time import sleep

# get access to sunrise and sunset
from astral import Location

from fractions import Fraction

# create a camera object
camera = PiCamera()

#set the image resolution
camera.resolution = (1024, 768)

#rotate the camera if upside-down
#camera.rotation = 180

#flip the camera on the horizontal
#camera.hflip = True

i = 0;

#record defaults
framerate = camera.framerate
shutter_speed = camera.shutter_speed
exposure_mode = camera.exposure_mode
iso = camera.iso

while True:

  # Get sunrise and sunset for Monroe, WA
  l = Location()
  l.latitude = 47.887059
  l.longitude = -121.8792998
  l.timezone = 'US/Pacific'

  sunrise = l.sun()['dawn']
  sunriseHour = int(sunrise.strftime('%H'))
  sunriseMinute = int(sunrise.strftime('%M'))
  sunset = l.sun()['sunset']
  sunsetHour = int(sunset.strftime('%H'))
  sunsetMinute = int(sunset.strftime('%M'))

  hours = int(datetime.datetime.now().strftime('%H'))
  minutes = int(datetime.datetime.now().strftime('%M'))
  seconds = int(datetime.datetime.now().strftime('%S'))
  #print 'hours='+hours+' minutes='+minutes+' seconds='+seconds
  if (hours > sunriseHour and hours < sunsetHour):
    #print 'work in the light'
    camera.framerate = framerate
    camera.shutter_speed = shutter_speed
    camera.exposure_mode = exposure_mode
    camera.iso = iso
  else:
    #print 'work in the dark'
    camera.framerate = Fraction(1,6)
    camera.shutter_speed = 600000
    camera.exposure_mode = 'off'
    camera.iso = 800

  filename = 'image'+str(i)+'.jpg'

  #save image locally
  camera.capture(filename)

  #invoke the script to upload the image
  subprocess.call('python save_image.py '+filename, shell=True)

  sleep(3)

  i = (i + 1) % 12