import time
import calendar
start = input("请输入开始日期,格式为年-月-日")
end = input("请输入结束日期,格式为年-月-日")
# 将日期转化为时间元祖
start_timetuple = time.strptime(start, "%Y-%m-%d")
end_timetuple = time.strptime(end, "%Y-%m-%d")
# 将时间元祖转化为字符串
start_timestamp = time.mktime(start_timetuple)
end_timestamp = time.mktime(end_timetuple)
# 定义容器
weekdays = []
# 判断日期是否小于等于结束日期
while start_timestamp <= end_timestamp:
start_timetuple = time.localtime(start_timestamp)
# 取出时间元祖中的星期数判断是否为周一至周五
if start_timetuple[6] == 0:
# 把当前的时间戳转化为时间元祖
start_timetuple = time.localtime(start_timestamp)
# 把当前的时间元祖格式化
f = time.strftime("%Y-%m-%d", start_timetuple)
# 放入容器列表中
weekdays.append(f)
elif start_timetuple[6] == 1:
start_timetuple = time.localtime(start_timestamp)
f = time.strftime("%Y-%m-%d", start_timetuple)
weekdays.append(f)
elif start_timetuple[6] == 2:
start_timetuple = time.localtime(start_timestamp)
f = time.strftime("%Y-%m-%d", start_timetuple)
weekdays.append(f)
elif start_timetuple[6] == 3:
start_timetuple = time.localtime(start_timestamp)
f = time.strftime("%Y-%m-%d", start_timetuple)
weekdays.append(f)
elif start_timetuple[6] == 4:
start_timetuple = time.localtime(start_timestamp)
f = time.strftime("%Y-%m-%d", start_timetuple)
weekdays.append(f)
# 日期加一天
start_timestamp += 86400
print(weekdays)
print("共"+str(len(weekdays))+"天")
如下图输出了2019年1月1日至2019年1月31日的周一至周五