You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python基于日期与时间的费率判断:扩展现有代码实现多日期规则

解决方案

以下是扩展后的完整代码,新增了日期判断逻辑,满足2023年2月25日沿用原规则返回A/B,2023年2月26日返回C/D的需求:

import numpy as np
import pandas as pd
import datetime

ts = ['2/25/2023 0:00', '2/25/2023 0:10', '2/25/2023 0:35', '2/25/2023 0:59', '2/25/2023 1:04', 
      '2/26/2023 0:05', '2/26/2023 0:38', '2/26/2023 1:07', '2/26/2023 10:08', '2/26/2023 10:59']

temp = ['0', '21', '20', '30', '40', '50', '6', '7', '8', '9']

df = pd.DataFrame(list(zip(ts, temp)), columns=['ts', 'temp'])
df['ts'] = pd.to_datetime(df['ts'])
df1 = df.set_index('ts')

def get_rate(row):
    # 指定2023年2月26日为特殊日期
    special_date = datetime.date(2023, 2, 26)
    if row.date() == special_date:
        # 特殊日期规则:分钟数小于30返回C,否则返回D
        return 'C' if row.minute < 30 else 'D'
    else:
        # 默认规则(含2023年2月25日):分钟数小于30返回A,否则返回B
        return 'A' if row.minute < 30 else 'B'

df1['Rate'] = df1.index.map(get_rate)
print(df1)

关键修改说明

  • 扩展get_rate函数,新增日期判断逻辑:通过row.date()提取时间索引的日期部分,与指定的特殊日期(2023-02-26)比对
  • 分分支处理费率规则:特殊日期返回C/D,其他日期(包括2023-02-25)沿用原逻辑返回A/B
  • 代码结构清晰,后续若需添加更多特殊日期的费率规则,只需新增elif分支即可

输出结果

运行代码后会得到如下符合需求的输出:

temp Rate
ts                            
2023-02-25 00:00:00    0    A
2023-02-25 00:10:00   21    A
2023-02-25 00:35:00   20    B
2023-02-25 00:59:00   30    B
2023-02-25 01:04:00   40    A
2023-02-26 00:05:00   50    C
2023-02-26 00:38:00    6    D
2023-02-26 01:07:00    7    C
2023-02-26 10:08:00    8    C
2023-02-26 10:59:00    9    D

内容的提问来源于stack exchange,提问作者Ashu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:05:32