吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1276|回复: 5
收起左侧

[Python 转载] 取一周开始结束日期

[复制链接]
zohoChou 发表于 2022-4-30 11:26
之前的一个excel要自动生成一周的日期(比如今天是4.30,应输出2022.4.25-2022.5.1)
本以为这种小需求网上一定有相关的轮子,不用自己重新造……万万没想想到没找到……(CSDN上的有发,但是无解析)
结果自己造轮子的时候发现要考虑一大堆东西……如果是跨年怎么办,跨月怎么办……然后就自己鼓捣了一个出来……


等我抽个空,直接拒绝引用,重写一个逻辑完整的出来(咕咕咕)


[Python] 纯文本查看 复制代码
import calendar
import datetime


today = datetime.datetime.now()
date = today.day  # 今天日期(int)下同
month = today.month
year = today.year

weekday = datetime.datetime.isoweekday(today)  # 取今天的星期数
if(weekday == 0):
    # 为了符合习惯,特进行重赋值
    weekday = 7

monthRange = calendar.monthrange(today.year, today.month)[1]
# 取本月共多少天


def first():
    result = date - weekday
    if(result < 0):  # 计算5号星期六的情况
        if(today.month == 1):  # 上月恰好为12月
            list_date = list(range(26, 32))  # 生成去年12月的日期列表,根据负数取日期
            first_date = str(today.year - 1) + "年12月" + \
                str(list_date[result]) + "日"
        else:  # 上月为1月等
            temp = calendar.monthrange(year, month - 1)
            list_date = list(range(temp - 5, temp + 1))
            first_date = str(today.year) + "年" + str(today.month - 1) +  \
                "月" + str(list_date[result]) + "日"  # 生成实际需要的日期(星期一对应的日期)
    else:  # 正常情况
        first_date = str(today.year) + "年" + str(today.month) +  \
            "月" + str(result + 1) + "日- "

    return first_date


def last():
    result = date - weekday + 7
    if(result > monthRange):
        if(today.month == 12):
            last_date = str(today.year + 1) + "年1月" +  \
                str(result - monthRange) + "日"
        else:
            last_date = str(today.year) + "年" + str(today.month + 1) +  \
                "月" + str(result - monthRange) + "日"
    else:
        last_date = str(today.year) + "年" + str(today.month) +  \
            "月" + str(result) + "日"
    return last_date


print(first() + last())

免费评分

参与人数 1吾爱币 +5 热心值 +1 收起 理由
苏紫方璇 + 5 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

夹克油 发表于 2022-4-30 13:07
大佬就是牛,需要什么样的程序,自己写!
shojnhv 发表于 2022-4-30 14:12
limuyan44 发表于 2022-4-30 12:47
[mw_shl_code=python,true]import pendulum as pdl

now = pdl.now()

学习了,以前也是自己写的代码
 楼主| zohoChou 发表于 2022-5-1 21:28
limuyan44 发表于 2022-4-30 12:47
[mw_shl_code=python,true]import pendulum as pdl

now = pdl.now()

!!!
多谢指路,之前真没发现还有其他轮子(笑哭
deepgo 发表于 2022-5-2 00:59
先存下以后备用
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-27 20:19

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表