在开发某个功能时需要计算当前时间往前推移N个月、半年、三年的时间,现有的datetime.timedelta()
只支持日、小时、分、秒、毫秒推移,不支持月与年。所以自己实现了一下月份与年的推移,并结合datetime.timedelta()
,最终实现完整的日期时间前后推移功能。
建议使用datetime.timedelta()
from datetime import datetime
from datetime import timedelta as td
def time_delata(sourcedate:datetime,days:int,hours:int,minutes:int,seconds:int,microseconds:int):
return sourcedate + td(days=days, hours=hours, minutes=minutes, seconds=seconds, microseconds=microseconds)
优点:官方模块,有持续维护,文档说明齐全
自定义代码实现月份、年份的前后推移
def month_delta(months):
month = sourcedate.month + months
if month % 12 == 0:
if month // 12 == 1:
year = sourcedate.year
else:
year = sourcedate.year + floor(months / 12)
month = 12
else:
year = sourcedate.year + floor(months / 12)
month = month % 12
day = min(sourcedate.day, calendar.monthrange(year, month)[1])
return datetime.datetime(year, month, day, hour=sourcedate.hour, minute=sourcedate.minute,
second=sourcedate.second,
microsecond=sourcedate.microsecond, )
def year_delta(years):
year = sourcedate.year +years
return datetime.datetime(year, month=sourcedate.month, day=sourcedate.day, hour=sourcedate.hour, minute=sourcedate.minute, second=sourcedate.second,microsecond=sourcedate.microsecond, )
将章节一与章节二的内容相结合,写一个代理方法,即可实现
一通搞完,发现居然有第三方库已经实现了这个功能,人都麻了。
不过使用第三方库也不是完全没有缺点。
优点:简单方便、高效
缺点:第三方库,不稳定,上次版本更新已经是在2021年,已经过了3年了
def timedelta(sourcedate,years, months, days, hours, minutes, seconds, microseconds):
dst_date = sourcedate
if years:
dst_date = dst_date + relativedelta(years=years)
if months:
dst_date = dst_date + relativedelta(months=months)
if days:
dst_date = dst_date + relativedelta(days=days)
if hours:
dst_date = dst_date + relativedelta(hours=hours)
if minutes:
dst_date = dst_date + relativedelta(minutes=minutes)
if seconds:
dst_date = dst_date + relativedelta(seconds=seconds)
if microseconds:
dst_date = dst_date + relativedelta(microseconds=microseconds)
return dst_date
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。