Python:关于datetime与int互转的自写库

手写一个关于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}")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值