Python 如何實現月份相加?

時間 2021-06-03 08:53:38

1樓:奚衡

受邀答題,自己DIY了乙個計算這個的函式,思路大致:

1 計算出這段指定時間的當天時間凌晨時間和疊加月後的凌晨時間

2 求出相差的天數

3 最後再加天數再指定的時間內疊加即可

#!/usr/bin/env python

# -*- coding: utf-8 -*-

from datetime import datetime, timedelta

def add_months(start, months):

_start = datetime(year=start.year, month=start.month, day=start.day)

_end = datetime(year=start.year+months/12 if months > 0 else start.year + -1*(abs(months)/12), \

month=start.month+months%12 if months > 0 else (start.month + -1*abs(months))%12, \

day=start.day)

diff_days = (_end - _start).days

end = start + timedelta(days=diff_days)

return end

if __name__ == "__main__":

now = datetime.now()

end = add_months(now, months=3)

print end

end = add_months(now, months=-4)

print end

2樓:

d1.replace(month=(d1.month + 3 - 1) % 12 + 1, year=d1.

year if d1.month < 10 else d1.year + 1)

python 如何實現遠端tail f?

37丫37 django channels寫個也不複雜,這裡有關於channels的介紹,也有實現tailf的例子 Django使用Channels實現WebSocket 上篇 guyskk tail f是不會結束的,所以你要開新執行緒去讀取日誌並寫入django response 並且respon...

python如何實現列表交叉合併

蓋世小猛男 all list length1 len res list length2 len res list2 if length1 length2 length length2 elif length1 length2 length length1 else length length1 fo...

如何用python實現行列互換?

程式設計小白一枚,使用python 3.6 笨辦法 b fori inrange len a 0 row forj inrange len a row.a j i b.row print b 以上寫成一句 print row i for rowina fori inrange len a 0 用函式...