文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Python实现日期判断和加减操作详解

2024-04-02 19:55

关注

python实现日期判断和加减操作

#====================================================
#时间相关
#====================================================
 
def if_workday(day_str, separator=""):
    """
    if a day is workday
    
    :param day_str: string of a day
    :param separator: separator of year, month and day, default is empty
    :return: True: is workday; False: not workday
    """
    spec = "%Y" + separator + "%m" + separator + "%d"
    day = datetime.strptime(day_str, spec).date()
    # Monday == 0 ... Sunday == 6
    if day.weekday() in [0, 1, 2, 3, 4]:
        return True
    else:
        return False
 
def if_weekend(day_str, separator=""):
    """
    if a day is weekend
    
    :param day_str: string of a day
    :param separator: separator of year, month and day, default is empty
    :return: True: is weekend; False: not weekend
    """
    spec = "%Y" + separator + "%m" + separator + "%d"
    day = datetime.strptime(day_str, spec).date()
    # Monday == 0 ... Sunday == 6
    if day.weekday() in [5, 6]:
        return True
    else:
        return False
 
def is_week_lastday():
    '''
    判断今天是否为周末,return the day of the week as an integer,Monday is 0 and Sunday is 6
    
    :return:
    '''
    
    now = (datetime.datetime.utcnow() + datetime.timedelta(hours=8))
    # 假如今天是周日
    todayIndex = now.weekday()
    # 如果今天是周日,则返回True
    if todayIndex == 6:
        print("todayIndex={},今天是周末...".format(todayIndex))
        return True
    else:
        print("todayIndex={},今天是周 {},不是周末...".format(todayIndex,int(todayIndex+1)))
        return False
    
def is_week_whichday(dayIndex=6):
    '''
    判断今天一周的哪一天,周一为0,周末为6,return the day of the week as an integer,Monday is 0 and Sunday is 6
    
    :return:
    '''
    
    now = (datetime.datetime.utcnow() + datetime.timedelta(hours=8))
    # 假如今天是周日
    todayIndex = now.weekday()
    # 如果今天是周日,则返回True
    if todayIndex == dayIndex:
        print("todayIndex={},今天是周 {},不是周 {}...".format(todayIndex, int(todayIndex+1),int(dayIndex+1)))
        return True
    else:
        print("todayIndex={},今天是周 {},不是周 {}...".format(todayIndex,int(todayIndex+1),int(dayIndex+1)))
        return False
 
def is_month_lastday():
    '''
    # 判断今天是否为月末
    
    :return:
    '''
    
    # 获得当月1号的日期
    start_date = datetime.date.today().replace(day=1)
    # 获得当月一共有多少天(也就是最后一天的日期)
    _, days_in_month = calendar.monthrange(start_date.year, start_date.month)
 
    todayIndex = time.strftime("%d", time.localtime())
    
    # 如果今天是周末,返回True
    if int(todayIndex) == int(days_in_month):
        print("start_date={},todayIndex={},days_in_month={},今天是月末...".format(start_date,todayIndex, days_in_month))
        return True
    else:
        print("start_date={},todayIndex={},days_in_month={},今天不是月末...".format(start_date,todayIndex , days_in_month))
        return False
 
def get_this_week_start():
    '''
    获取本周第一天日期
    
    :return:
    '''
    now = datetime.datetime.now()
    this_week_start = now - timedelta(days=now.weekday())
    this_week_end = now + timedelta(days=6 - now.weekday())
    print('--- this_week_start = {} this_week_end = {}'.format(this_week_start, this_week_end))
    print('--- this_week_start = {} '.format(this_week_start))
    return this_week_start
    
def get_this_week_end():
    '''
    # 获取本周最后一天日期
    
    :return:
    '''
    
    now = datetime.datetime.now()
    this_week_start = now - timedelta(days=now.weekday())
    this_week_end = now + timedelta(days=6 - now.weekday())
    print('--- this_week_start = {} this_week_end = {}'.format(this_week_start, this_week_end))
    print('--- this_week_end = {}'.format(this_week_end))
    return this_week_end
 
def get_last_month_start(now = datetime.datetime.now()):
    
    now = datetime.datetime.strptime(now, "%Y-%m-%d")
    # 本月第一天和最后一天
    this_month_start = datetime.datetime(now.year, now.month, 1)
    this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
    # print('--- this_month_start = {} this_month_end = {}'.format(this_month_start, this_month_end))
    
    # 上月第一天和最后一天
    last_month_end = this_month_start - timedelta(days=1)+ datetime.timedelta(hours=23, minutes=59, seconds=59)
    last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
    # print('--- last_month_end = {} last_month_start = {}'.format(last_month_end, last_month_start))
    print('--- last_month_start = {}'.format(last_month_start))
    return last_month_start
 
def get_last_month_end(now = datetime.datetime.now()):
    now = datetime.datetime.strptime(now, "%Y-%m-%d")
    # 本月第一天和最后一天
    this_month_start = datetime.datetime(now.year, now.month, 1)
    this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
    # print('--- this_month_start = {} this_month_end = {}'.format(this_month_start, this_month_end))
    
    # 上月第一天和最后一天
    last_month_end = this_month_start - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
    last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
    # print('--- last_month_end = {} last_month_start = {}'.format(last_month_end, last_month_start))
    print('--- last_month_end = {} '.format(last_month_end))
    return last_month_end
 
def get_this_month_start(now = datetime.datetime.now()):
    now = datetime.datetime.strptime(now, "%Y-%m-%d")
    # 本月第一天和最后一天
    this_month_start = datetime.datetime(now.year, now.month, 1)
    this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
    # print('--- this_month_start = {} this_month_end = {}'.format(this_month_start, this_month_end))
    
    # 上月第一天和最后一天
    last_month_end = this_month_start - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
    last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
    # print('--- last_month_end = {} last_month_start = {}'.format(last_month_end, last_month_start))
    print('--- this_month_start = {} '.format(this_month_start))
    return this_month_start
 
def get_this_month_end(now = datetime.datetime.now()):
    now=datetime.datetime.strptime(now, "%Y-%m-%d")
    # 本月第一天和最后一天
    this_month_start = datetime.datetime(now.year, now.month, 1)
    # this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
    
    if now.month < 12:
        this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
    elif  now.month >= 12:
        this_month_end = datetime.datetime(now.year, now.month , now.day+30) + datetime.timedelta(hours=23, minutes=59, seconds=59)
 
        
    # print('--- this_month_start = {} this_month_end = {}'.format(this_month_start, this_month_end))
    
    # 上月第一天和最后一天
    last_month_end = this_month_start - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
    last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
    # print('--- last_month_end = {} last_month_start = {}'.format(last_month_end, last_month_start))
    # print('--- this_month_end = {} '.format(this_month_end))
    return str(this_month_end)
 
#从一个时间段获取其中的每一天,可以自定义时间间隔
def get_every_day(start = '2018-01-01',end = '2021-01-01',daysCount=1):
    '''
    从一个时间段获取其中的每一天,可以自定义时间间隔
    
    :param start: str类型,开始时间,如:'2018-01-01'
    :param end: str类型,结束时间,如:'2021-01-01'
    :param daysCount: int类型,每一个时间间隔,默认为1天
    :return:
    '''
    datestart = datetime.datetime.strptime(start, '%Y-%m-%d')
    dateend = datetime.datetime.strptime(end, '%Y-%m-%d')
    
    date_list=[]
    while datestart < dateend:
        datestart += datetime.timedelta(days=daysCount)
        date_str=str(datestart.strftime('%Y-%m-%d'))
        # print('date_str={}'.format(date_str))
        date_list.append(date_str)
 
    print('date_list={}'.format(date_list))
    return date_list
 
#从一个时间段获取其中的每一月,可以自定义时间间隔
def getBetweenEveryMonth(begin_date,end_date):
    date_list = []
    begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
    end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
    # end_date = datetime.datetime.strptime(time.strftime('%Y-%m-%d', time.localtime(time.time())), "%Y-%m-%d")
    while begin_date <= end_date:
        date_str = begin_date.strftime("%Y-%m-%d")
        begin_date = add_months_start(begin_date, 1)
        date_end=get_this_month_end(date_str)
        date_list.append((date_str+' 00:00:00',date_end))
        
    print('date_list={}'.format(date_list))
    return date_list
 
 
def add_months_start(dt, months):
    month = int(dt.month - 1 + months)
    year = int(dt.year + month / 12)
    month = int(month % 12 + 1)
    day = min(dt.day, calendar.monthrange(year, month)[1])
    return dt.replace(year=year, month=month, day=day)
 
def add_months_end(dt, months):
    month = int(dt.month - 1 + months)
    year = int(dt.year + month / 12)
    month = int(month % 12 + 1)
    day = max(dt.day, calendar.monthrange(year, month)[1])
    return dt.replace(year=year, month=month, day=day)

到此这篇关于Python实现日期判断和加减操作详解的文章就介绍到这了,更多相关Python日期判断 加减操作内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯