python3获取当前年份的每个月第一天和最后一天日期
程序员文章站
2022-05-10 19:37:57
...
python3获取从一月到当前月份每月的首天和最后一天日期
1.代码
import datetime, calendar
from datetime import timedelta
# 获取当前年份每个月的首天和最后一天,本月最后一天取本日数据
def getYearMonthsDay():
result = {}
# 获取当前年份
thisYear = datetime.date.today().year
# 获取当前月份
thisMonth = datetime.date.today().month
# 获取当前天
thisDay = datetime.date.today().day
for x in range(1, thisMonth + 1):
monthRange = calendar.monthrange(thisYear, x)[1]
startDay = str(thisYear) + "-" + str(x).zfill(2) + "-01"
endDay = str(thisYear) + "-" + str(x).zfill(2) + "-"
#如果不想本月取最后一天取当前日期,可不做判断,直接用endDay = endDay + str(monthRange).zfill(2)
if x == thisMonth:
endDay = endDay + str(thisDay).zfill(2)
else:
endDay = endDay + str(monthRange).zfill(2)
result[str(x)] = [startDay, endDay]
return result
2.测试结果
测试代码:
print("今天是:" + str(datetime.date.today()))
print("获取跨度日期:" + str(getYearMonthsDay()))
结果:
今天是:2019-12-04
获取跨度日期:{'1': ['2019-01-01', '2019-01-31'], '2': ['2019-02-01', '2019-02-28'], '3': ['2019-03-01', '2019-03-31'], '4': ['2019-04-01', '2019-04-30'], '5': ['2019-05-01', '2019-05-31'], '6': ['2019-06-01', '2019-06-30'], '7': ['2019-07-01', '2019-07-31'], '8': ['2019-08-01', '2019-08-31'], '9': ['2019-09-01', '2019-09-30'], '10': ['2019-10-01', '2019-10-31'], '11': ['2019-11-01', '2019-11-30'], '12': ['2019-12-01', '2019-12-04']}
上一篇: 台积电:摩尔定律未死 我们的5nm工艺密度、性能最强
下一篇: css(平时记录的)
推荐阅读