手写一个关于datetime互转Int的库,自用。
import datetime
import math
import time as t
"""
year: 2010 *10^10
month: 12*10^8
day :31*10^6
hour :23*10^4
minute: 59*10^2
second:59
2010,12,31,23,59,59
"""
YU = 10**10
MU = 10**8
DU = 10**6
HHU = 10**4
MMU = 10**2
### 2010-12-30
yu = 10**4
mu = 10**2
## 23:59:59
hhu = 10**4
mmu = 10**2
def dt2int(dtime):
y = dtime.year * YU
m = dtime.month * MU
d = dtime.day * DU
hh = dtime.hour * HHU
mm = dtime.minute * MMU
ss = dtime.second
return y+m+d+hh+mm+ss
dtime = datetime.datetime(2010,12,12,12,23,30)
def int2dt(ndtime):
y = math.floor(ndtime /YU)
rem = ndtime -y*YU
m = math.floor(rem/MU)
rem = rem - m*MU
d = math.floor(rem/DU)
rem = rem -d*DU
hh = math.floor(rem/HHU)
rem = rem -hh*HHU
mm = math.floor(rem/MMU)
rem = rem -mm*MMU
ss = rem
return datetime.datetime(y,m,d,hh,mm,ss)
def dt2inttuple(dtime):
y = dtime.year * yu
m = dtime.month * mu
d = dtime.day
hh = dtime.hour * hhu
mm = dtime.minute * mmu
ss = dtime.second
return (y+m+d,hh+mm+ss)
def inttuple2dt(ntuple):
assert len(ntuple)==2
ymd_rem = ntuple[0]
hms_rem = ntuple[1]
print(f" {ymd_rem} {hms_rem}")
## ymd
y = math.floor(ymd_rem /yu)
ymd_rem = ymd_rem -y*yu
m = math.floor(ymd_rem/mu)
ymd_rem = ymd_rem - m*mu
d = ymd_rem
## hh,mm,ss
hh = math.floor(hms_rem/hhu)
hms_rem = hms_rem -hh*hhu
mm = math.floor(hms_rem/mmu)
hms_rem = hms_rem -mm*mmu
ss = hms_rem
#print(f"y :{y} m:{m} d:{d} hh:{hh} mm:{mm} ss:{ss}")
return datetime.datetime(y,m,d,hh,mm,ss)
t0 = t.time()
n = dt2int(dtime)
t1 = t.time()
dt = int2dt(n)
t2 = t.time()
ntuple = dt2inttuple(dtime)
t3 = t.time()
dt2 = inttuple2dt(ntuple)
t4 = t.time()
assert dt == dtime
assert dtime == dt2
print(f"dtime :{dtime } -> int :{n} cost time :{t1-t0} seconds")
print(f"int : {n} -> dtime :{dt} cost time: {t2-t1} seconds")
print(f"dtime :{dtime} -> inttuple :{ntuple} cost time :{t3-t2} seconds")
print(f"ntuple :{ntuple} -> dt :{dt2} cost time :{t4-t3}")
输出:[这里cost time不严谨,备注]
print(f"dtime :{dtime } -> int :{n} cost time :{t1-t0} seconds")
print(f"int : {n} -> dtime :{dt} cost time: {t2-t1} seconds")
print(f"dtime :{dtime} -> inttuple :{ntuple} cost time :{t3-t2} seconds")
print(f"ntuple :{ntuple} -> dt :{dt2} cost time :{t4-t3}")