在Python中使用小时和星期几计算日期

huangapple go评论60阅读模式
英文:

Calculating dates in Python with dependies on hour and name of day

问题

我正在开发一个应用程序,用户可以预订汽车,并且预订的费用取决于预订发生的小时和星期几。

费用计算规则如下:

  1. 周一至周五上午7点至晚上7点(白天):每小时2.00美元
  2. 周一至周五上午7点至上午7点(夜间):每小时0.50美元
  3. 周六和周日(白天和夜间每小时):每小时0.50美元

示例预订:

开始:周一,2023/02/06 - 上午07:00
结束:周一,2023/02/20 - 上午07:00

计算:

10个工作日(周一至周五白天)每天12小时 * 2.00 = 240.00
10个工作日(周一至周五夜间)每天12小时 * 0.50 = 60.00
4个周末日,每天24小时 * 0.50美元 = 48.00

这将导致总费用为348.00

我想知道如何使用Python函数解决此问题,该函数根据上述3条规则计算开始日期和结束日期。

我甚至不知道如何开始提取开始日期和结束日期中的小时和日期。

英文:

I am developing an application where users can make a reservation for a car and the fee for the reservation depends on which hours and which day of the week the reservation takes places.

The rules for the fee calculation are:

  1. Monday until Friday 7am - 7 pm (during the day): 2.00 Dollars per hour
  2. Monday until Friday 7am - 7 am (during the night): 0.50 Dollars per hour
  3. Saturday and Sunday (every hour during the day and night): 0.50 Dollars per hour

Example reservation:

start: Monday, 2023/02/06 - 07:00 am
end: Monday, 2023/02/20 - 07:00 am

Calculation:

10 weekdays (monday-friday during the day) with 12 hours * 2.00 = 240.00 
10 weekdays (monday-friday during the night) with 12 hours * 0.50 = 60.00
4 weekend days with 24 hours per day * 0.50 CHF	= 48.00

This results in a total fee of 348.00

I am wondering how I could solve this with a function in python with calculates the start date and end dates with dependies on the 3 rules from above.

I even don't know how to start in order to extract the hours and days from the start date and end date.

答案1

得分: 1

为了计算给定预订的费用,您可以编写一个Python函数,该函数以预订的开始日期和结束日期作为输入,并使用datetime模块从日期中提取小时数和天数。

import datetime

def calculate_reservation_fee(start_date, end_date):
    weekdays_day_rate = 2.00  # 白天工作日费率
    weekdays_night_rate = 0.50  # 夜间工作日费率
    weekend_rate = 0.50  # 周末费率

    total_fee = 0.00

    # 遍历预订期间的所有小时
    current_date = start_date
    while current_date < end_date:
        hour = current_date.hour
        day_of_week = current_date.weekday()  # 0代表星期一,6代表星期日

        if day_of_week < 5 and 7 <= hour < 19:  # 工作日白天
            total_fee += weekdays_day_rate
        elif day_of_week < 5:  # 工作日夜间
            total_fee += weekdays_night_rate
        else:  # 周末
            total_fee += weekend_rate

        # 移动到下一个小时
        current_date += datetime.timedelta(hours=1)

    return total_fee
英文:

To calculate the fee for a given reservation, you can write a Python function that takes the start and end dates of the reservation as inputs, and uses datetime module to extract the hours and days from the dates.

import datetime

def calculate_reservation_fee(start_date, end_date):
    weekdays_day_rate = 2.00  # rate for weekdays during the day
    weekdays_night_rate = 0.50  # rate for weekdays during the night
    weekend_rate = 0.50  # rate for weekends
    
    total_fee = 0.00
    
    # iterate over all hours in the reservation period
    current_date = start_date
    while current_date &lt; end_date:
        hour = current_date.hour
        day_of_week = current_date.weekday()  # 0 is Monday, 6 is Sunday
        
        if day_of_week &lt; 5 and 7 &lt;= hour &lt; 19:  # weekday during the day
            total_fee += weekdays_day_rate
        elif day_of_week &lt; 5:  # weekday during the night
            total_fee += weekdays_night_rate
        else:  # weekend
            total_fee += weekend_rate
        
        # move to the next hour
        current_date += datetime.timedelta(hours=1)
    
    return total_fee

答案2

得分: 0

我创建了一个自定义类,基于 datetime 模块构建,覆盖了减法方法 __sub__

cost 方法定义了每个小时段的价格应该是多少,使用了你上面提到的规则。

从 pandas 导入的 date_range 函数用于生成两个日期之间的每个小时,然后我应用 cost 函数来计算总价格。

import datetime as dt
from pandas import date_range

class Rental(dt.datetime):
    def __sub__(self, other):
        times = date_range(self, other, freq='H', inclusive='left')
        return sum(self.cost(d) for d in times)

    @staticmethod
    def cost(time):
        if time.weekday() > 4:
            return 0.5
        if 7 <= time.hour < 19:
            return 2
        return 0.5
print(Rental(year=2022, month=3, day=20, hour=0) - Rental(year=2022, month=4, day=3, hour=0))
>>> 348.0
英文:

I made an example with a custom class built on top of the datetime module, that overrides the subtract method __sub__.

The cost method defines what the price should be in each hour interval using your rules above.

The function date_range from pandas is used to generate each hour between the two dates, which I then apply the cost function on to get the total price

import datetime as dt
from pandas import date_range


class Rental(dt.datetime):
    def __sub__(self, other):
        times = date_range(self, other, freq=&#39;H&#39;, inclusive=&#39;left&#39;)
        return sum(self.cost(d) for d in times)

    @staticmethod
    def cost(time):
        if time.weekday() &gt; 4:
            return 0.5
        if 7 &lt;= time.hour &lt; 19:
            return 2
        return 0.5
print(Rental(year=2022, month=3, day=20, hour=0) - Rental(year=2022, month=4, day=3, hour=0))
&gt;&gt;&gt; 348.0

答案3

得分: 0

这段代码接受与您示例中类似的字符串输入,执行后将打印出348作为所期望的价格。它使用一个列表来存储所有的价格,因此如果价格发生变化,以后修改起来不会太困难。当index到达周价格列表的末尾时,index将被设置回零,这样您可以在每周结束时继续累积小时数。

import datetime

# 假设您的输入格式如下
input_start = "Monday, 2023/02/06 - 07:00 am"
input_end = "Monday, 2023/02/20 - 07:00 am"

# 剥离星期几,因为它无关紧要
start = datetime.datetime.strptime(input_start.split(", ")[1], "%Y/%m/%d - %I:%M %p")
end = datetime.datetime.strptime(input_end.split(", ")[1], "%Y/%m/%d - %I:%M %p")

# 现在创建一个包含一周内每小时价格的列表hourly_prices_week
# 列表的长度应为168(一周168小时)

# 为了更快地构建它,首先填充工作日和周末
hourly_prices_weekday = [0.5] * 7 + [2] * 12 + [0.5] * 5
hourly_prices_weekend = [0.5] * 24

# 添加5个工作日,然后是2个周末日
# 注意价格从星期一的开始
hourly_prices_week = hourly_prices_weekday * 5 + hourly_prices_weekend * 2

print(hourly_prices_week)  # [ 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 2, 2, 2, ....]
print(len(hourly_prices_week))  # 168

# 查找开始时间和结束时间之间有多少小时
hours = (end - start).total_seconds() / 3600
print(hours)  # 336

# 确定开始时间在hourly_prices中的索引
index = 0  # 这是星期一的开始
index += start.weekday() * 24  # 前进多少天(星期一是0)
index += start.hour  # 前进多少小时(小时为0-23)
print(index)  # 7

price = 0
while hours > 0:
    price += hourly_prices_week[index]
    index += 1
    if index >= len(hourly_prices_week):
        index = 0
    hours -= 1

print(price)  # 348
英文:

This snippet takes input strings as in your example and when executed prints 348 as the desired price. It uses a list to store all prices so it isn't too hard to modify in future if prices change. When index gets to the end of the weekly prices list index will be set back to zero so you can keep adding up the hours as the weeks roll over.

import datetime

# assuming your input format is strings like this
input_start = &quot;Monday, 2023/02/06 - 07:00 am&quot;
input_end = &quot;Monday, 2023/02/20 - 07:00 am&quot;

# cut out the weekday as it doesn&#39;t matter
start = datetime.datetime.strptime(input_start.split(&quot;, &quot;)[1], &quot;%Y/%m/%d - %I:%M %p&quot;)
end = datetime.datetime.strptime(input_end.split(&quot;, &quot;)[1], &quot;%Y/%m/%d - %I:%M %p&quot;)

# now make a list hourly_prices_week of all the prices of each hour in the week
# the list should be 168 in length (168 hours in a week)

# to build it faster fill in the weekday and weekend first
hourly_prices_weekday = [0.5] * 7 + [2] * 12 + [0.5] * 5
hourly_prices_weekend = [0.5] * 24

# add the 5 weekdays and then 2 weekend days
# note the prices start at the begining of monday
hourly_prices_week = hourly_prices_weekday * 5 + hourly_prices_weekend * 2

print(hourly_prices_week)  # [ 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 2, 2, 2, ....]
print(len(hourly_prices_week))  # 168

# find out how many hours are between start and end times
hours = (end - start).total_seconds() / 3600
print(hours)  # 336

# determine what index of hourly_prices your start time is in
index = 0  # this is start of monday
index += start.weekday() * 24  # go forward however many days (monday is 0)
index += start.hour  # go forward however many hours (hour is 0-23)
print(index)  # 7

price = 0
while hours &gt; 0:
    price += hourly_prices_week[index]
    index += 1
    if index &gt;= len(hourly_prices_week):
        index = 0
    hours -= 1

print(price)  # 348

huangapple
  • 本文由 发表于 2023年3月31日 20:32:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898565.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定