有一个大数组,其中 column[0] 对应于日期,col[1]=month, col[2]=year 和 col[3]=hours(后者是一个浮点数,还包含有关分钟和秒的信息分数),将这些列转换为日期时间数组的最有效方法是什么?
更新如下:我修改了 dt.datetime 函数,因此它可以处理数组输入以及小数年、月等。我还没有彻底测试过,可能有更优雅的方法可以做到这一点,但这里就可以了。
from __future__import division
def getrem(input):
"this function yields the value behind the decimal point"
import numpy as np
output=abs(input-np.fix(input))
return output
def datenum(Yr,Mo=1,Da=1,Hr=0,Mi=0,Se=0,Ms=0):
"this function works as regular datetime.datetime, but allows for float input"
import numpy as np
import datetime as dt
import calendar
#correct faulty zero input
if Mo<1:
Mo+=1
if Da<1:
Da+=1
#distribute the year fraction over days
if getrem(Yr)>0:
if calendar.isleap(np.floor(Yr)):
fac=366
else:
fac=365
Da=Da+getrem(Yr)*fac
Yr=int(Yr)
#if months exceeds 12, pump to years
while int(Mo)>12:
Yr=Yr+1
Mo=Mo-12
#distribute fractional months to days
if getrem(Mo)>0:
Da=Da+getrem(Mo)*calendar.monthrange(Yr,int(Mo))[1]
Mo=int(Mo)
#datetime input for 28 days always works excess is pumped to timedelta
if Da>28:
extraDa=Da-28
Da=28
else:
extraDa=0
# sometimes input is such that you get 0 day or month values, this fixes this anomaly
if int(Da)==0:
Da+=1
if int(Mo)==0:
Mo+=1
#datetime calculation
mytime=dt.datetime(int(Yr),int(Mo),int(Da))+dt.timedelta(days=extraDa+getrem(Da),hours=Hr,minutes=Mi,seconds=Se,microseconds=Ms)
return mytime
def araydatenum(*args):
mydatetimes=[datenum(*[a.squeeze()[x] for a in args]) for x in range(len(args[0].squeeze()))]
return mydatetimes