python有点新,但是尝试将其用于卫星轨道分析。我真的没有得到datetime对象和方法。我希望能够将datetime对象传递给一个函数,该函数接受与datetime基本上相同的格式(年,月,日,小时,分钟,秒)的参数。下面的代码有效,但是必须有更好的方法。请赐教。谢谢!
import jday
import datetime
jdate = jday.JD(2015,12,1,22,8,0) # example
now1 = datetime.datetime.now().strftime("%Y,%m,%d,%H,%M,%S")
now2 = now1.split(",")
now3 = [int(i) for i in now2]
jdatenow = jday.JD(*now3)
print jdatenow
jday模块是从David Vallado的Astrodynamics源代码的Matlab移植而来的。
import math as m
def JD(yr, mon, day, hr, min, sec):
jd = 367.0 * yr - m.floor(
(7 * (yr + m.floor( (mon + 9) / 12.0) ) ) * 0.25 ) + m.floor(
275 * mon / 9.0 ) + day + 1721013.5 + (
(sec/60.0 + min ) / 60.0 + hr ) / 24.0
return jd
最佳答案
鉴于您已经移植了JD代码,因此可以将其作为jday模块进行控制,也许您正在寻找装饰器。这样做的明显好处是不破坏该函数的原始签名(对于现有的客户端代码),但是根据您的要求增加了日期参数的便利性。
还创建了一个jday2模块,该模块与原始jday模块相同,但其JD()函数改为直接接受日期对象。如果不需要任何向后兼容性,这是最简单的解决方案。
请参见下面的工作示例代码:
jday.py
import math as m
import functools
def date_support_wrapper(f):
""" Wraps JD and provides a way to pass a date param
:param f: the original function
:return: the wrapper around the original function
"""
@functools.wraps(f)
def wrap(*args, **kwargs):
if 'date' in kwargs:
d = kwargs['date']
return f(yr=d.year, mon=d.month, day=d.day, hr=d.hour, min=d.minute, sec=d.second)
return f(*args, **kwargs)
return wrap
@date_support_wrapper
def JD(yr, mon, day, hr, min, sec):
jd = 367.0 * yr - m.floor(
(7 * (yr + m.floor((mon + 9) / 12.0))) * 0.25) + m.floor(
275 * mon / 9.0) + day + 1721013.5 + (
(sec / 60.0 + min) / 60.0 + hr) / 24.0
return jd
jday2.py
import math as m
def JD(dt):
""" Same calculation as JD but accepts a date object argument
:param dt: the date object
:return: the JD result
"""
yr, mon, day, hr, min, sec = dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second
jd = 367.0 * yr - m.floor(
(7 * (yr + m.floor((mon + 9) / 12.0))) * 0.25) + m.floor(
275 * mon / 9.0) + day + 1721013.5 + (
(sec / 60.0 + min) / 60.0 + hr) / 24.0
return jd
以及示例客户端代码:
client.py
import datetime
import jday
import jday2
# The date we are interested in
a = dict(year=2015, month=12, day=1, hour=22, minute=8, second=0)
dt = datetime.datetime(**a) # 2015-12-01 22:08:00
# The original signature of the function
jdate1 = jday.JD(a['year'], a["month"], a["day"], a["hour"], a["minute"], a["second"])
# 2457358.422222222
# The new signature that accepts a normal date object
# Note that we use keyword "date" argument
jdate2 = jday.JD(date=dt)
# 2457358.422222222
# The new signature that accepts a normal date object
jdate3 = jday2.JD(dt)
# 2457358.422222222