Octoth0rpe
Octoth0rpe

Reputation: 2267

localtime not actually giving localtime

there's obviously a time module that works in combination with this problem, but I have not found it yet. I'm simply trying to use Pyephem on a Raspberry Pi to find out what time sunrise and sunset is for my latitude longitude coordinates. the code is quite simply this:

import ephem
import datetime 
import time
now = datetime.datetime.now()
gmNow = time.mktime(time.localtime()) 
Vancouver = ephem.Observer()
Vancouver.lat = 49.2878
Vancouver.horizon = 0
Vancouver.lon = -123.0502
Vancouver.elevation = 80
Vancouver.date = now
# Vancouver.date = time.localtime()

sun = ephem.Sun()

print("sunrise is at",ephem.localtime(Vancouver.next_rising(sun)))
print("sunset is going to be at ",ephem.localtime(Vancouver.next_setting(sun)))
print("now is ",now)
print("gmNow is",gmNow)

what exports, when that runs is wrong by 8 hours though. so it appears that the ephem.localtime() is not actually running.

pi@raspberrypi ~ $ sudo python3 vivarium_sun.py 
sunrise is at 2014-09-19 12:55:56.000004
sunset is going to be at  2014-09-19 00:52:30.000004
now is  2014-09-19 06:22:24.014859
gmNow is 1411132944.0

It's driving me nuts, and it's obviously one of those simple things once it's figured out, so I'm going to the hive mind here.

EDIT** Just typing 'date' into the command line of the Raspberry Pi returns the following:

pi@raspberrypi ~ $ date
Fri Sep 19 18:41:42 PDT 2014

which is accurate.

Upvotes: 2

Views: 1849

Answers (1)

jfs
jfs

Reputation: 414345

You should pass datetime.utcnow() to the observer instead of your local time.

ephem expects latitude and longitude in radians if passed as floats, use strings instead:

from datetime import datetime, timezone

import ephem

now = datetime.now(timezone.utc)
Vancouver = ephem.Observer()
Vancouver.lat = '49.2878'
Vancouver.horizon = 0
Vancouver.lon = '-123.0502'
Vancouver.elevation = 80
Vancouver.date = now
sun = ephem.Sun(Vancouver)

print("sunrise is at", ephem.localtime(Vancouver.next_rising(sun)))
print("sunset is going to be at ", 
      ephem.localtime(Vancouver.next_setting(sun)))
print("now is ",now.astimezone())

Output

sunrise is at 2014-09-20 06:55:38.000005
sunset is going to be at  2014-09-19 19:16:38.000004
now is  2014-09-19 19:15:04.171486-07:00

Upvotes: 1

Related Questions