python 获取时间段内所有天 求本周的星期一 时间段内每个星期的周一日期 某个月份有多少天 时间段内所有月份 某月的第一天和最后一天

获取时间段内所有天

def dateRange(beginDate, endDate):
    dates = []
    dt = datetime.datetime.strptime(beginDate, "%Y-%m-%d")
    date = beginDate[:]
    while date <= endDate:
        dates.append(date)
        dt = dt + datetime.timedelta(1)
        date = dt.strftime("%Y-%m-%d")
    return dates

dateRange('2019-11-25', '2019-12-03')
['2019-11-25','2019-11-26','2019-11-27','2019-11-28','2019-11-29','2019-11-30','2019-12-01','2019-12-02','2019-12-03']

求本周的星期一

def get_current_week(x_time):
    monday = datetime.datetime.strptime(x_time, "%Y-%m-%d")
    one_day = datetime.timedelta(days=1)
    while monday.weekday() != 0:
        monday -= one_day
    return monday.strftime('%Y-%m-%d')

get_current_week('2020-01-14')
'2020-01-13'

时间段内每个星期的周一日期

def weekRange(beginDate, endDate):
    date_week = []
    date_list = dateRange(beginDate, endDate)
    for i in date_list:
        dt = datetime.datetime.strptime(i, "%Y-%m-%d")
        if dt.weekday() == 0:
            date_week.append(i)
    if date_week[0] != date_list[0]:
        date_week.insert(0,get_current_week(date_list[0]))

    return date_week

weekRange('2019-11-12', '2019-12-11')
['2019-11-11', '2019-11-18', '2019-11-25', '2019-12-02', '2019-12-09']

某个月份有多少天

def get_day(year,month):
    if (month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
        return 31
    elif (month == 4 or month == 6 or month == 9 or month == 11):
        return 30
    elif month == 2 and ((year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)):
        return 29
    else:
        return 28

get_day(2020,1)
31

时间段内所有月份

def get_each_month(start_month, end_month):
    start_month = start_month.replace('-','.')
    end_month = end_month.replace('-','.')

    if str(start_month).count('.') != 1 or str(end_month).count('.') != 1:
        print("Parameter Error: Pls input a string such as '2019.01'")
        return[]
    if int(str(start_month).split('.')[1]) > 12 or int(str(end_month).split('.')[1]) > 12:
        print('Parameter Error: Pls input correct month range such as between 1 to 12')
        return[]
    if int(str(start_month).split('.')[1]) == 0:
        print('Parameter Error: Pls input correct month range such as between 1 to 12')
        return[]
    start = datetime.datetime.strptime(start_month, "%Y.%m")
    end = datetime.datetime.strptime(end_month, "%Y.%m")
    month_count = rrule.rrule(rrule.MONTHLY,dtstart=start,until=end).count() #计算总月份数
    if end < start:
        print("Parameter Error: Pls input right date range,start_month can't latter than end_month")
        return []
    else:
        list_month = []
        year = int(str(start)[:7].split('-')[0])       #截取起始年份
        for m in range(month_count):  #利用range函数填充结果列表
            month = int(str(start)[:7].split('-')[1])  #截取起始月份,写在for循环里,作为每次迭代的累加基数
            month = month + m
            if month > 12:
                if month%12 > 0:
                    month = month%12  #计算结果大于12,取余数
                    if month==1:
                        year += 1     #只需在1月份的时候对年份加1,注意year的初始化在for循环外
                else:
                    month = 12
            if len(str(month))==1:
                list_month.append(str(year) + '.0' + str(month))
            else:
                list_month.append(str(year) + '.' + str(month))
            list_month = [i.replace('.','-') for i in list_month]
        return list_month

get_each_month('2019-3','2020-01')
['2019-03','2019-04','2019-05','2019-06','2019-07','2019-08','2019-09','2019-10','2019-11','2019-12','2020-01']

某月的第一天和最后一天

def get_current_month_start_and_end(date):
    """
    年份 date(2017-09-08格式)
    :param date:
    :return:本月第一天日期和本月最后一天日期
    """
    if date.count('-') != 2:
        raise ValueError('- is error')
    year, month = str(date).split('-')[0], str(date).split('-')[1]
    end = calendar.monthrange(int(year), int(month))[1]
    start_date = '%s-%s-01' % (year, month)
    end_date = '%s-%s-%s' % (year, month, end)
    return [start_date, end_date]

get_current_month_start_and_end('2017-09-08')
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值