【说站】python输入数字变成月份
2023-06-13 09:13:16 时间
python输入数字变成月份
1、思路说明
可计算给定区间的时间差,即两者之间共包含几个月。然后由第一个月(开始时间)逐渐累积,最后得到给定时间区间所有月份的清单。
2、时间差计算:我们可以使用第三方库 dateutil中的rrule.count函数来实现。
Impor tdatetime from dateutil importrrule
start=datetime.datetime.strptime('2019.01','%Y.%m')
end=datetime.datetime.strptime('2019.05','%Y.%m')print(start.month)
rrule.rrule(rrule.MONTHLY,dtstart=start,until=end).count()
3、每月累积计算:在这里,我们可以使用for循环和range()函数,根据总月数,逐步累积,例如:2019.01-2019.05共5个月,从0到4迭代,从1+0=1到1+4=5,就可以得到所有月份;此外,当月迭代累积结果超过12时,将累积结果除以12取余,并将年份加1,就可以得到正确的年月时间。
importdatetimefrom dateutil importrruledefget_each_month(start_month, end_month):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 or int(str(end_month).split('.')[1]) == 12: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
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 +mif 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))return list_month
以上就是python输入数字变成月份的方法,基本的流程分享给大家,看懂后可以进行实例部分的尝试。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
相关文章
- Python怎么输入小数和整数_python输入非负整数
- python安装不了whl文件_Python安装whl文件过程图解
- python基础知识
- python 主函数 输入
- gyp ERR! stack Error: Can't find Python executable 'python'
- 【说站】python for…in循环的使用
- 【说站】python如何输入数据类型检查
- Python的特点是什么_python具有的特点
- 解决python封装Logging模块后,log位置显示错误的问题
- Python保存json_python保存json文件
- 在python中用来安装第三方库的常用工具_什么库用于安装管理Python扩展包
- python deepcopy函数_Python deepcopy
- 【python】SAX和DOM处理XML文件
- Python 自动化业务服务监控
- python-Python与SQLite数据库-SQLite数据库的基本知识(一)
- python-Python与PostgreSQL数据库-使用Python执行PostgreSQL查询(二)
- 一个非常高效的提取内容关键词的python代码详解编程语言
- Python去除list中的重复元素的最简单办法详解编程语言
- Python输出函数print()总结(python print())详解编程语言
- Python与MongoDB 无缝连接(python连接mongodb)
- Python与MySQL实现数据分析的完美组合(mysql中python)
- python读取csv文件示例(python操作csv)
- 使用python编写脚本获取手机当前应用apk的信息
- Python的批量远程管理和部署工具Fabric用法实例