前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python日期时间前后推移

Python日期时间前后推移

原创
作者头像
法号戒糖
发布2024-01-19 13:38:20
2390
发布2024-01-19 13:38:20
举报
文章被收录于专栏:菜狗的踩坑记录与技术分享

Python日期时间前后推移

在开发某个功能时需要计算当前时间往前推移N个月、半年、三年的时间,现有的datetime.timedelta()只支持日、小时、分、秒、毫秒推移,不支持月与年。所以自己实现了一下月份与年的推移,并结合datetime.timedelta(),最终实现完整的日期时间前后推移功能。

一、日、小时、分、秒、毫秒推移

建议使用datetime.timedelta()

代码语言:python
代码运行次数:0
复制
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)

优点:官方模块,有持续维护,文档说明齐全

二、月份、年份推移

自定义代码实现月份、年份的前后推移

1. 月份推移

代码语言:python
代码运行次数:0
复制
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, )

2. 年份推移

代码语言:python
代码运行次数:0
复制
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, )

三、年、月、日、小时、分、秒、毫秒推移

将章节一与章节二的内容相结合,写一个代理方法,即可实现

四、第三方库python-dateutil

一通搞完,发现居然有第三方库已经实现了这个功能,人都麻了。

不过使用第三方库也不是完全没有缺点。

优点:简单方便、高效

缺点:第三方库,不稳定,上次版本更新已经是在2021年,已经过了3年了

代码语言:python
代码运行次数:0
复制
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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Python日期时间前后推移
    • 一、日、小时、分、秒、毫秒推移
      • 二、月份、年份推移
        • 1. 月份推移
        • 2. 年份推移
      • 三、年、月、日、小时、分、秒、毫秒推移
        • 四、第三方库python-dateutil
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档