Python Ephem / Datetime计算

时间:2010-04-06 19:23:37

标签: python datetime astronomy

输出应将第一个日期作为“日”处理,其次作为“夜晚”处理。我现在已经玩了几个小时了,无法弄清楚我做错了什么。有什么想法吗?

修改 我认为问题是由于我的日期比较实现

输出:

$ python time_of_day.py
* should be day:
event date:  2010/4/6 16:00:59
prev rising:  2010/4/6 09:24:24
prev setting:  2010/4/5 23:33:03
next rise:  2010/4/7 09:22:27
next set:  2010/4/6 23:34:27
day
* should be night:
event date:  2010/4/6 00:01:00
prev rising:  2010/4/5 09:26:22
prev setting:  2010/4/5 23:33:03
next rise:  2010/4/6 09:24:24
next set:  2010/4/6 23:34:27
day

time_of_day.py

import datetime
import ephem # install from http://pypi.python.org/pypi/pyephem/

#event_time is just a date time corresponding to an sql timestamp
def type_of_light(latitude, longitude, event_time, utc_time, horizon):

  o = ephem.Observer()
  o.lat, o.long, o.date, o.horizon = latitude, longitude, event_time, horizon

  print "event date ", o.date

  print "prev rising: ", o.previous_rising(ephem.Sun())
  print "prev setting: ", o.previous_setting(ephem.Sun())
  print "next rise: ", o.next_rising(ephem.Sun())
  print "next set: ", o.next_setting(ephem.Sun())


  if o.previous_rising(ephem.Sun()) <= o.date <= o.next_setting(ephem.Sun()):
    return "day"
  elif o.previous_setting(ephem.Sun()) <= o.date <= o.next_rising(ephem.Sun()):
    return "night"
  else:
    return "error"


print "should be day: ", type_of_light('45.959','-66.6405','2010/4/6 16:01','-4', '-6')

print "should be night: ", type_of_light('45.959','-66.6405','2010/4/6 00:01','-4', '-6')

1 个答案:

答案 0 :(得分:7)

o.date将始终位于o.previous_settings和o.next_rising;之间,因此您可以这样检查:

if o.previous_rising(ephem.Sun()) > o.previous_setting(ephem.Sun()):
  return "day"
elif:
  return "night"