Page 1 of 1

Daylight Hours

Posted: Thu Jan 07, 2016 11:04 am
by RDS
Is there any Python code that calculates Daylight hours for a given location?

Re: Daylight Hours

Posted: Thu Jan 07, 2016 11:10 am
by RaTTuS
probably yes but see
https://www.risacher.org/sunwait/
for the way to do it

Re: Daylight Hours

Posted: Thu Jan 07, 2016 11:30 am
by DougieLawson
If you really insist on doing it in python http://rhodesmill.org/pyephem/

I run sunwait from crontab and it runs a simple bash script that wiggles a GPIO pin and writes a file /var/run/lightordark.

Code: Select all

3 3 * * * root /usr/local/bin/sunwait civ up +0:01:00 51.000N 1.000W ; /usr/local/bin/sunny.sh light;
3 14 * * * root /usr/local/bin/sunwait civ down -0:01:00 51.000N 1.000W ; /usr/local/bin/sunny.sh dark;

Code: Select all

#!/bin/bash

NOW=$(date '+%T %d/%m')
echo $1' @ '$NOW > /var/run/lightordark

if [ "$1" == "light" ]; then
  /usr/local/bin/gpio -g pwm 18 0
else
  /usr/local/bin/gpio -g pwm 18 1023
fi

Re: Daylight Hours

Posted: Thu Jan 07, 2016 7:13 pm
by RDS
@DougieLawson
Thank you for that link. I want to use Python, because that is the language I have decided to use for my RPi. The program I want to use the information for, is my Solar Panel monitoring program, written in Python.

Re: Daylight Hours

Posted: Thu Jan 07, 2016 7:14 pm
by RDS
@RaTTuS
Thank you for taking the time to reply but I will stick with a Python solution.

Re: Daylight Hours

Posted: Thu Jan 07, 2016 11:56 pm
by DougieLawson
Then the answer is pyephem.

Code: Select all

import sys
import ephem
from numpy import pi
from datetime import date, time, datetime
from struct import *

def main():

        base = datetime(1970,1,1)
        sun = ephem.Sun()
        home = ephem.Observer()

        home.lat, home.lon = '51.000','-1.000'
        home.date = ephem.now()

        sun.compute(home)

        home.horizon = '-6'
        civil_start, civil_end = (home.next_rising(sun, use_center=True),
                        home.next_setting(sun, use_center=True))

        d = {}
        d[home.date] = " Date / time now: " + str(ephem.localtime(home.date))
        d[civil_end] = " Civil twilight ends: " + str(ephem.localtime(civil_end))
        d[civil_start] = " Civil twilight starts: " + str(ephem.localtime(civil_start))

        for time in sorted(d.keys()):
                print d[time]
                print "---"
        if civil_start < civil_end:
                print " Start less than end : dark"
        if civil_start >= civil_end:
                print " Start greater than/equal end: daylight"
        print " Now  : ", ephem.now()
        print " Start: ", ephem.Date(civil_start)
        print " End  : ", ephem.Date(civil_end)
        print "---"

if __name__ == "__main__":
        main()

Re: Daylight Hours

Posted: Fri Jan 08, 2016 4:48 am
by stderr
RDS wrote:@DougieLawson
Thank you for that link. I want to use Python, because that is the language I have decided to use for my RPi.
You probably shouldn't try to do everything you are doing with the pi using one language, certainly not avoiding all helper programs. I'm not saying you shouldn't use python for this aspect of what you are doing, just that making some kind of vow of purity to python seems like a good way to miss out on some sometimes perhaps easier answers.

Re: Daylight Hours

Posted: Fri Jan 08, 2016 12:51 pm
by DougieLawson
stderr wrote:
RDS wrote:@DougieLawson
Thank you for that link. I want to use Python, because that is the language I have decided to use for my RPi.
You probably shouldn't try to do everything you are doing with the pi using one language, certainly not avoiding all helper programs. I'm not saying you shouldn't use python for this aspect of what you are doing, just that making some kind of vow of purity to python seems like a good way to miss out on some sometimes perhaps easier answers.
That's especially true because python2 vs python3 is such a complete mess.

Pick the language that makes the programming task easiest. Or pick an obscure language that you don't yet know well and use it as a learning opportunity. Don't just stick with python.

Re: Daylight Hours

Posted: Fri Jan 08, 2016 3:14 pm
by hippy
stderr wrote:
RDS wrote:@DougieLawson
Thank you for that link. I want to use Python, because that is the language I have decided to use for my RPi.
You probably shouldn't try to do everything you are doing with the pi using one language, certainly not avoiding all helper programs. I'm not saying you shouldn't use python for this aspect of what you are doing, just that making some kind of vow of purity to python seems like a good way to miss out on some sometimes perhaps easier answers.
On the other hand, sticking to that purity and just using Python does have its advantages, even if it may make some things harder. I also favour the 'Python only' philosophy for programming on a Pi, especially where code is not Pi specific. It makes cross-platform development and deployment so much easier and any code potentially more useful to a wider audience.

I'm not particularly a Python 'fanboi'; there are things about it which I dislike, but the benefits generally outweigh the disadvantages. I would encourage people to use Python where they can and I would be delighted if there were more enthusiasm from the MicroPython team to open the door for 'bare metal Python' on a Pi.

Re: Daylight Hours

Posted: Sat Jan 09, 2016 11:37 am
by RDS
DougieLawson wrote:Then the answer is pyephem.
Thank you, this looks like just what I need but once again, I am falling at virtually the first hurdle!
I get a lot of parenthesis print errors , that I believe I have sorted out. (I use Python 3)
However, I then get the following error:
ImportError: No module named 'ephem'

I tried sudo apt-get install ephem from the command line but that reports:
E: Unable to locate package ephem

Questions:
1) How do I load up the modules required
2) Is the code a Python 3 script

Sorry for really simple questions because despite having a fully running Python program to monitor my Solar Panels, I am still struggling with the basics of modules

Re: Daylight Hours

Posted: Sat Jan 09, 2016 11:42 am
by RDS
@stderr
Thanks, I think that is probably very good advice but Python seemed quite similar in a number of respects to languages I have used before e.g. BBC basic, MS visual basic so looked a good place to start.

I will look to use other languages, because I have so far failed completely to make any progress with another Project I wanted to get working using Python.

Re: Daylight Hours

Posted: Sat Jan 09, 2016 11:45 am
by RDS
@hippy
Thank you for your support. I do think I will have to broaden my horizons though in general but my reason for using Python is explained in my post above, plus the fact that I wanted to be able to incorporate the 'Daylight hours' code into my existing Python program.

Re: Daylight Hours

Posted: Sat Jan 09, 2016 12:00 pm
by jojopi
RDS wrote:E: Unable to locate package ephem
The apt-get package name for a Python3 module would normally be python3-module. However, only the most popular Python modules are packaged as part of Raspbian.

You need to use Python's own packaging system, pip:

Code: Select all

sudo apt-get install python3-pip
sudo pip3 install PyEphem
(PyEphem produces tons of warnings as it compiles, but it seems to work okay.)

Re: Daylight Hours

Posted: Sat Jan 09, 2016 12:56 pm
by RDS
jojopi wrote:
RDS wrote:(PyEphem produces tons of warnings as it compiles, but it seems to work okay.)
Excellent!
That is working now. Thank you very much.

Ideally, I would like to be able to solve questions like that myself but I notice (for example) that you install PyEphem rather than just ephem. Is that just experience or where can I pick that knowledge up.

Re: Daylight Hours

Posted: Sun Dec 09, 2018 2:08 pm
by RDS

Code: Select all

import sys
import ephem
from numpy import pi
from datetime import date, time, datetime
from struct import *

def main():

        base = datetime(1970,1,1)
        sun = ephem.Sun()
        home = ephem.Observer()
        home.lat, home.lon = '51.000','-1.000'   # Example from original Program
       
        home.date = ephem.now()

        sun.compute(home)

        home.horizon = '-6'
        civil_start, civil_end = (home.next_rising(sun, use_center=True),
                        home.next_setting(sun, use_center=True))

        d = {}
        d[home.date] = " Date / time now: " + str(ephem.localtime(home.date))
        d[civil_end] = " Civil twilight ends: " + str(ephem.localtime(civil_end))
        d[civil_start] = " Civil twilight starts: " + str(ephem.localtime(civil_start))

        for time in sorted(d.keys()):
                print (d[time])
                print ("---")
        if civil_start < civil_end:
                print (" Start less than end : dark")
        if civil_start >= civil_end:
                print (" Start greater than/equal end: daylight")
        print (" Now  : ", ephem.now())
        print (" Start: ", ephem.Date(civil_start))
        print (" End  : ", ephem.Date(civil_end))
        print ("---")

if __name__ == "__main__":
        main()
The above program, provided to me above, works perfectly and shows the start and end of daylight hours for any given lat / long co-ordinates.

I would now like to incorporate this in my own Solar Panel program but by having a simple variable, for example daylight = 1 when it is light or daylight = 0, when it is dark.

The way it is currently written seems extremely complicated, with statements like d={} and lots of other commands that contain dots (.), that I just do not understand.

Is it possible to really simplify this program to give me just:
daylight = 0 or daylight = 1.

Re: Daylight Hours

Posted: Sun Dec 09, 2018 4:25 pm
by hippy
RDS wrote:
Sun Dec 09, 2018 2:08 pm
Is it possible to really simplify this program to give me just:
daylight = 0 or daylight = 1.
I'm not familiar with that module bit it appears to me that the start and end of daylight for the day is given by ephem.localtime(civil_start) and ephem.localtime(civil_end) so would guess something like -

Code: Select all

if ( currentLocalTime >= ephem.localtime(civil_start) ) and ( currentLocalTime <= ephem.localtime(civil_end) ):
  daylight = 1
else:
  daylight = 0
Orv as a boolean -

Code: Select all

isDaylight = ( currentLocalTime >= ephem.localtime(civil_start) ) and ( currentLocalTime <= ephem.localtime(civil_end) )

Re: Daylight Hours

Posted: Sun Dec 09, 2018 4:28 pm
by scruss
jojopi wrote:
Sat Jan 09, 2016 12:00 pm
RDS wrote:E: Unable to locate package ephem
The apt-get package name for a Python3 module would normally be python3-module. However, only the most popular Python modules are packaged as part of Raspbian.
PhEphem for both Python 2 and 3 are in the repos:

Code: Select all

python-ephem - Compute positions of the planets and stars with Python 2
python3-ephem - Compute positions of the planets and stars with Python 3
Dougie's code is in Python 2, so the OP will want:

Code: Select all

sudo apt install python-ephem
If the code needs to work under Python 3, install python3-ephem and use 2to3 to convert Dougie's code.

PyEphem is deprecated by its author, who recommends its replacement Skyfield.

Re: Daylight Hours

Posted: Sun Dec 09, 2018 7:51 pm
by BlueWolf
I use Pysolar for my Raspberries that control the lights when it gets dark outside. Works in Python3. Although it won't tell you the times of sunrise and sunset, it is however very easy to get it to the current angle of the sun. So then it is just as easy as making a logic of 'if angle < 0' etc.

Here is an example of one that will give you the angle every two seconds

Code: Select all

import datetime
import time
import pysolar.solar

LOC = 52.541105, 4.065300

while 1:
    now = datetime.datetime.now()
    angle = pysolar.solar.get_altitude(*LOC, now)
    print("Angle = {}".format(angle))
    time.sleep(2)

Re: Daylight Hours

Posted: Sun Dec 09, 2018 10:47 pm
by RDS
@Bluewolf, scruss and hippy
Thank you all for your help and support.
There should be enough there to enable me to update my program.