Python生成两位数日期、两位数月日
-
1.在开始和结束日期设置范围,这里是从大月到小月生成;
2.可以将下面"月减一和天减一",减法修改成加法 ”月加一和天加一“ 来实现小月到大月。
3.代码里将结果保存到列表中,你可以根据实际情况放到其他类型变量里。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | ## 开始、结束日期 date_start = '1202' date_end = '0930' ## 全局变量 _list_month_day = [] ## 判断date_start_month月有多少天,并设置date_start_month月的天数 def set_month_days(date_start_month): month = date_start_month ## 31天的月份 month_31day = "01030507081012" ## 30天的月份 month_30day = "04060911" ## 默认day是28天 day = 28 ## 如果 month_31day 或 month_30day 里包含 month 为真,则设置对应天数 if month in month_31day: day = 31 elif month in month_30day: day = 30 ## 给调用者返回天数 return day def add_month_day(): date_start_month = date_start[ 0 : 2 ] date_start_day = date_start[ 2 : 4 ] ## 如果月的第一位是0则取第二位 if date_start_month[: 1 ] = = "0" : date_start_month = date_start_month[ 1 : 2 ] ## 如果日的第一位是0则取第二位 if str (date_start_day)[: 1 ] = = "0" : date_start_day = date_start_day[ 1 : 2 ] ## 循环产生月和日 while True : ## 将上一次循环设置成int类型,转回str类型 date_start_month = str (date_start_month) date_start_day = str (date_start_day) ## 如果日等于1号,则月份减一, ## 并调用set_month_days函数,获取本月天数 if date_start_day = = "1" : ## 月减一 date_start_month = int (date_start_month) - 1 date_start_day = set_month_days( str (date_start_month)) else : ## 天减一 date_start_day = int (date_start_day) - 1 ## month_day值:1.拼接月+日,不足两位,左补0 ## 2.上面运算把月和日转成int型,拼接需要转str型 month_day = "{:0>2}" . format ( eval ( str (date_start_month))) + "{:0>2}" . format ( eval ( str (date_start_day))) ## 将生成的月和日添加到全局变量列表中,方便其他类或方法使用 global _list_month_day _list_month_day.append(month_day) ## 如果当前月日和设置的date_end相等,则退出while循环 if date_end = = month_day: break if ( __name__ = = 'main' or __name__ = = '__main__' ): add_month_day(); print (f "\n结果:\n{_list_month_day}" ) |
结果:
__EOF__
分类:
Python & Jython
标签:
python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!