Python 按月增加datetime月份的问题,pythondatetime,今天要为大家收集分享的P
Python 按月增加datetime月份的问题,pythondatetime,今天要为大家收集分享的P
今天要为大家收集分享的Python学习代码为:Python 按月增加datetime月份的问题源码。可能有同学看不明白什么是Python 按月增加datetime?其实简单的理解python datetime增加月份的问题,就是一些人的日常工作是需要对月份加减进行相关操作计算。
DateTime是什么:DateTime是时间类型,datetime是Python处理日期和时间的标准库。还有python time模块
Python 按月增加datetime月份的问题源码如下:(Python源码中注释部分多为英文,大家可自行翻译)
#coding=utf-8import datetime# input datetime1, and an month offset# return the result datetimedef datetime_offset_by_month(datetime1, n = 1): # create a shortcut object for one day one_day = datetime.timedelta(days = 1) # first use div and mod to determine year cycle q,r = divmod(datetime1.month + n, 12) # create a datetime2 # to be the last day of the target month datetime2 = datetime.datetime( datetime1.year + q, r + 1, 1) - one_day''' if input date is the last day of this month then the output date should also be the last day of the target month, although the day www.iplaypy.com may be different. for example: datetime1 = 8.31 datetime2 = 9.30''' if datetime1.month != (datetime1 + one_day).month: return datetime2''' if datetime1 day is bigger than last day of target month, then, use datetime2 for example: datetime1 = 10.31 datetime2 = 11.30''' if datetime1.day >= datetime2.day: return datetime2''' then, here, we just replace datetime2's day with the same of datetime1, that's ok.''' return datetime2.replace(day = datetime1.day)#------------编橙之家-----www.iplaypy.com---------------d1 = datetime.datetime(2008, 8, 17)d2 = datetime_offset_by_month(d1, 13)print '2008-8-17 + 13 month'print d2printd1 = datetime.datetime(2008, 8, 31)d2 = datetime_offset_by_month(d1, 13)print '2008-8-31 + 13 month'print d2printd1 = datetime.datetime(2007, 1, 30)d2 = datetime_offset_by_month(d1, 13)print '2007-1-30 + 13 month'print d2printresult = """2008-8-17 + 13 month2009-09-17 00:00:002008-8-31 + 13 month2009-09-30 00:00:002007-1-30 + 13 month2008-02-29 00:00:00"""
编橙之家文章,
相关内容
- Python方法解决Url与Tinyurl地址互换问题,pythontinyurl,Pyt
- Python简易邮件查看器源码示例详解,python查看器,Pytho
- Python将汉字数字转换成阿拉伯数字的方法,python阿拉伯
- Python筛法求质数(素数)的生成器示例,python质数,本篇
- Python实现跨平台获取按键方法源码示例,python源码,本文
- Python计算n*n网格生成树数目的方法,python网格,Python计算
- Python实现HTML颜色和RGB颜色互转的方法,pythonrgb,本文是
- Python随机产生迷宫生成算法源码,python算法,用Python语言
- Python方法如何将普通IP转换为十进制IP,python十进制,P
- Python组合生成与数量计算的实现方法,python组合数量计
评论关闭