写在前面的话
疫情期间嘛,我自己造了个随机填写体温的轮子
然后悲哀的发现没法直接生成我要的日期,即一周开始时的日期和结束时的日期,生成格式为(例:2021年12月31日-2022年1月6日)
所以自己开始造轮子,本以为随手引用一个库就完事了,万万没想到麻烦多多一下为完整代码记录
完整代码及解析
import calendar
import datetime
today = datetime.datetime.now()
# 取今天日期以及星期等信息
date = today.day
# 取今天日期
month = today.month
# 取今天月份
year = today.year
# 取年份
weekday = datetime.datetime.isoweekday(today)
# 取今天星期几
if(weekday == 0):
weekday = 7
# 因为星期天被定义为0,特重新定义以符合习惯
monthRange = calendar.monthrange(today.year, today.month)[1]
# 取每月的天数
def first():
# 取本星期开始的日期
result = date-weekday
if(result < 0):
# 计算5号星期六的情况
if(today.month == 1): # 若上月恰好为12月(本月为1月)
list_date = list(range(26, 32)) # 生成去年12月的日期列表,根据负数取日期
first_date = str(today.year-1) + "年12月"+str(list_date[result])+"日"
# 上月为1月需要把年减一
else:
# 上个月是2月等
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())
over!
版权声明:本文为qq_43084170原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。