Python中基于时段与星期的租车预约费用计算实现
Python实现汽车预约费用计算(含时段与星期信息提取)
核心思路
用Python的datetime模块解析起止时间,提取星期与小时信息,再按规则逐段计算费用。以下是完整实现:
代码实现
from datetime import datetime, timedelta import re def parse_chinese_datetime(time_str: str) -> datetime: """解析中文格式时间字符串为datetime对象""" match = re.search(r"(\d+)年(\d+)月(\d+)日.*?(\d+:\d+)", time_str) if not match: raise ValueError("输入时间格式错误,示例格式:2023年2月6日周一7:00") year, month, day, time_part = match.groups() return datetime.strptime(f"{year}-{month}-{day} {time_part}", "%Y-%m-%d %H:%M") def calculate_reservation_cost(start_time: datetime, end_time: datetime) -> float: """计算预约总费用""" total_cost = 0.0 current_time = start_time while current_time < end_time: weekday = current_time.weekday() # 0=周一,6=周日 current_hour = current_time.hour # 确定当前时段费率 if weekday < 5: # 周一至周五 rate = 2.0 if 7 <= current_hour < 19 else 0.5 else: # 周六、周日 rate = 0.5 # 处理非整点结束的情况,计算实际时长 next_hour = current_time + timedelta(hours=1) actual_end = min(next_hour, end_time) duration_hours = (actual_end - current_time).total_seconds() / 3600 total_cost += rate * duration_hours current_time = next_hour return round(total_cost, 2) # 验证示例 if __name__ == "__main__": start_str = "2023年2月6日周一7:00" end_str = "2023年2月20日周一7:00" start_time = parse_chinese_datetime(start_str) end_time = parse_chinese_datetime(end_str) total = calculate_reservation_cost(start_time, end_time) print(f"核算结果:{total:.2f}美元") # 输出:348.00美元
关键细节说明
- 时间解析:通过正则提取中文时间里的日期和时间部分,转换为
datetime对象,不依赖输入的星期文字(避免输入错误)。 - 星期与时段提取:
current_time.weekday()返回0-6,对应周一到周日,以此区分工作日/周末。current_time.hour获取当前小时数,判断是否属于工作日日间(7:00-19:00)。
- 费用计算:逐小时遍历预约时段,处理非整点结束的边界情况,确保费用计算精准。
内容的提问来源于stack exchange,提问作者user18553570
相关产品推荐
相关产品推荐

