python 判断两个时间的月份差

#! /usr/bin/env python
# -*- coding:utf-8 -*-

from datetime import datetime,timedelta
import time

#import datetime
import arrow

a='target_display_price_20180701.xlsx'
a_date = ['201807', '201808', '201809', '201810', '201811', '201812', '201901', '201902', '201903', '201904', '201905', '201906']
a_date1 = []
#计算月份两个年月的月份差值
#1.将两个str型的时间转换为datetime型:
start_date = datetime.strptime(a[-13:-7], "%Y%m")
end_date = datetime.strptime(a_date[-1], "%Y%m")
print '时间为%s,%s'%(start_date,end_date)
#2.使用Arrow 对象
def months(str1,str2):
    year1=str1.year
    year2=str2.year
    month1=str1.month
    month2=str2.month
    num=(year1-year2)*12+(month1-month2)
    return num
print months(end_date,start_date)
bb=arrow.get(str(start_date), 'YYYY-MM-DD HH:mm:ss')

for x in range(0,months(end_date,start_date)+1):
    a_date1.append(bb.shift(months=+x).format("YYYYMM"))
print a_date1

 

运行结果:
时间为2018-07-01 00:00:00,2019-06-01 00:00:00
11
[u'201807', u'201808', u'201809', u'201810', u'201811', u'201812', u'201901', u'201902', u'201903', u'201904', u'201905', u'201906']

 

### 判断日期是否在特定月份区间 为了判断一个日期是否位于特定的月份范围内,在 Python 中可以利用 `datetime` 库来处理日期对象并比较它们所处的时间范围。 ```python from datetime import datetime def is_within_month_range(date, start_month, end_month): """ Check if given date falls within specified months. Parameters: date (str or datetime): Date to be checked; accepts both string and datetime object. start_month (int): Start month of the range (inclusive). end_month (int): End month of the range (inclusive). Returns: bool: True if date is within the month range, False otherwise. Examples: >>> is_within_month_range("2023-09-15", 6, 9) True >>> is_within_month_range(datetime(2023, 1, 1), 6, 9) False """ # Convert input date into a datetime object if it's not already one if isinstance(date, str): date = datetime.strptime(date, "%Y-%m-%d") # Ensure start_month does not exceed end_month by wrapping around year-end if start_month <= end_month: return start_month <= date.month <= end_month else: # Handle cases where the period crosses over December-January boundary return start_month <= date.month or date.month <= end_month # Example usage print(is_within_month_range("2023-07-20", 6, 8)) # Output should be True print(is_within_month_range("2023-05-20", 6, 8)) # Output should be False ``` 此函数能够接收字符串形式或 `datetime` 对象作为输入参数,并返回布尔值表示该日期是否落在指定的两个月份之间。对于跨越年尾的情况也进行了特别考虑,使得像十一月到次年的二月这样的查询成为可能[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值