写在前面的话
疫情期间嘛,我自己造了个随机填写体温的轮子
然后悲哀的发现没法直接生成我要的日期,即一周开始时的日期和结束时的日期,生成格式为(例: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
monthRange = calendar.monthrange(today.year, today.month)[1]
def first():
result = date-weekday
if(result < 0):
if(today.month == 1):
list_date = list(range(26, 32))
first_date = str(today.year-1) + "年12月"+str(list_date[result])+"日"
else:
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!
|