|
|
欢迎来到 FishC!你的问题很棒,这确实是打卡计数中常见的情况。
要解决缺勤问题,我们需要记录每次打卡的实际日期,而不是简单计算天数差。以下是两种解决方案:
方案一:使用列表记录每次打卡日期(适合数据量小的情况)
- from datetime import date
- # 模拟已经记录的打卡日期
- checkin_dates = [
- date(2026, 3, 31), # 第1天
- date(2026, 4, 1), # 第2天
- date(2026, 4, 3), # 第4天(4月2日缺勤)
- # ... 其他打卡日期
- ]
- name = 'helen_h'
- today = date.today()
- # 如果今天还没记录,就添加到列表
- if today not in checkin_dates:
- checkin_dates.append(today)
- # 计算实际打卡天数
- actual_days = len(checkin_dates)
- print(f'欢迎{name}!今天是你报道打卡的第{actual_days}天')
- print(f'实际打卡日期:{sorted(checkin_dates)}')
复制代码
方案二:使用文件或数据库记录(推荐,数据持久化)
- from datetime import date
- import json
- import os
- name = 'helen_h'
- today = date.today()
- record_file = f'{name}_checkin.json'
- # 如果记录文件不存在,创建初始记录
- if not os.path.exists(record_file):
- with open(record_file, 'w') as f:
- json.dump([str(date(2026, 3, 31))], f) # 第一天
- # 读取历史记录
- with open(record_file, 'r') as f:
- dates_str = json.load(f)
- # 转换为日期对象
- checkin_dates = [date.fromisoformat(d) for d in dates_str]
- # 如果今天还没记录,就添加并保存
- if today not in checkin_dates:
- checkin_dates.append(today)
- with open(record_file, 'w') as f:
- # 保存为字符串格式
- dates_str = [d.isoformat() for d in checkin_dates]
- json.dump(dates_str, f)
- actual_days = len(checkin_days)
- print(f'欢迎{name}!今天是你报道打卡的第{actual_days}天')
- print(f'历史打卡次数:{actual_days}次')
复制代码
关键思路:
1. 记录每次打卡的 实际日期,而不是计算连续天数
2. 每次打卡时检查是否已记录过当天
3. 实际打卡天数 = 已记录日期的数量
这样即使中间缺勤,也能正确统计实际打卡次数。你可以根据需求选择适合的方案!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|