1

I struggling to find an elegant way to set the ephem observer time to midnight local time. That is convert from midnight local time to ephem's UTC.

ephem uses next_rising to find the next sunrise time. Problem is if the local time is already past sunrise if gives you tomorrows sunrise.

I want to set my observer time to midnight local time so the next_rising , next_setting and next_transit are for the current day.

Going round in circles with python datetime stuff.

import ephem

home = ephem.Observer()
home.date = ephem.now()
home.lat = str(-37.8136)
home.lon = str(144.9631)

sunrise = home.next_rising( ephem.Sun() )

print home.date
# 2018/3/13 05:54:04

print ephem.localtime( home.date )
# 2018-03-13 16:54:03.000001 - current date is 13th March

print sunrise
# 2018/3/13 20:16:38 - sunrise in UTC

print ephem.localtime( sunrise )
# 2018-03-14 07:16:37.000002 -  next date sunrise 14th March
mdh
  • 21
  • 4

1 Answers1

1

Using this post How do I get the UTC time of "midnight" for a given timezone?

The following works

#!/usr/bin/env python
from datetime import datetime, time
import pytz # pip instal pytz
import ephem

tz = pytz.timezone("Australia/Melbourne") # choose timezone

today = datetime.now(tz).date()

# assert that there is no dst transition at midnight (`is_dst=None`)
midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None)

# convert to UTC 
fmt = '%Y-%m-%d %H:%M:%S'
print midnight.astimezone(pytz.utc).strftime(fmt)

home = ephem.Observer()
home.date = ephem.now()
home.date = ephem.Date( midnight.astimezone(pytz.utc).strftime(fmt) )

print home.date
mdh
  • 21
  • 4
  • Yes, this looks like it would work! You can probably remove the line `home.date = ephem.now()` and have the code still work, as the following line overwrites the value anyway. – Brandon Rhodes Mar 24 '18 at 11:29