RDS
Posts: 712
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Daylight Hours

Thu Jan 07, 2016 11:04 am

Is there any Python code that calculates Daylight hours for a given location?

User avatar
RaTTuS
Posts: 10305
Joined: Tue Nov 29, 2011 11:12 am
Location: North West UK

Re: Daylight Hours

Thu Jan 07, 2016 11:10 am

probably yes but see
https://www.risacher.org/sunwait/
for the way to do it
How To ask Questions :- http://www.catb.org/esr/faqs/smart-questions.html
WARNING - some parts of this post may be erroneous YMMV

1QC43qbL5FySu2Pi51vGqKqxy3UiJgukSX
Covfefe

User avatar
DougieLawson
Posts: 35340
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Daylight Hours

Thu Jan 07, 2016 11:30 am

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
Note: Having anything remotely humorous in your signature is completely banned on this forum.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

RDS
Posts: 712
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Daylight Hours

Thu Jan 07, 2016 7:13 pm

@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.
Last edited by RDS on Fri Jan 08, 2016 7:00 pm, edited 1 time in total.

RDS
Posts: 712
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Daylight Hours

Thu Jan 07, 2016 7:14 pm

@RaTTuS
Thank you for taking the time to reply but I will stick with a Python solution.

User avatar
DougieLawson
Posts: 35340
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Daylight Hours

Thu Jan 07, 2016 11:56 pm

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()
Note: Having anything remotely humorous in your signature is completely banned on this forum.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

stderr
Posts: 2178
Joined: Sat Dec 01, 2012 11:29 pm

Re: Daylight Hours

Fri Jan 08, 2016 4:48 am

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.

User avatar
DougieLawson
Posts: 35340
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Daylight Hours

Fri Jan 08, 2016 12:51 pm

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.
Note: Having anything remotely humorous in your signature is completely banned on this forum.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

hippy
Posts: 5328
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: Daylight Hours

Fri Jan 08, 2016 3:14 pm

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.

RDS
Posts: 712
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Daylight Hours

Sat Jan 09, 2016 11:37 am

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

RDS
Posts: 712
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Daylight Hours

Sat Jan 09, 2016 11:42 am

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

RDS
Posts: 712
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Daylight Hours

Sat Jan 09, 2016 11:45 am

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

User avatar
jojopi
Posts: 3074
Joined: Tue Oct 11, 2011 8:38 pm

Re: Daylight Hours

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.

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

RDS
Posts: 712
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Daylight Hours

Sat Jan 09, 2016 12:56 pm

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.

RDS
Posts: 712
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Daylight Hours

Sun Dec 09, 2018 2:08 pm

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.

hippy
Posts: 5328
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: Daylight Hours

Sun Dec 09, 2018 4:25 pm

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

User avatar
scruss
Posts: 2252
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON
Contact: Website

Re: Daylight Hours

Sun Dec 09, 2018 4:28 pm

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.
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.

BlueWolf
Posts: 33
Joined: Fri Aug 25, 2017 8:59 pm

Re: Daylight Hours

Sun Dec 09, 2018 7:51 pm

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)

RDS
Posts: 712
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Daylight Hours

Sun Dec 09, 2018 10:47 pm

@Bluewolf, scruss and hippy
Thank you all for your help and support.
There should be enough there to enable me to update my program.

Return to “Python”