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

如何转换当前日期为函数参数,满足定时脚本的多场景接口调用?

每日定时请求脚本实现方案

需求明确

  • 脚本支持每日定时执行,接收参数status,可选值为past或present
  • 时间与日期规则:
    1. present模式:使用取整后的当前日期时间;past模式:使用取整后的当前时间减4小时对应的日期时间
    2. 时间需向下取整至最近的半小时(例:2022-11-08 05:32运行时,present对应05:30,past对应01:30)
  • 根据参数拼接URL并发起GET请求,past模式的URL需在取整后的目标时间基础上再减1小时(参考示例代码逻辑)

实现代码

import requests
from datetime import datetime, timedelta

def get_request(past_or_present):
    # 获取当前时间并向下取整到最近的半小时
    now = datetime.now()
    rounded_minute = (now.minute // 30) * 30
    rounded_time = now.replace(minute=rounded_minute, second=0, microsecond=0)
    
    # 根据模式调整时间
    if past_or_present == "past":
        # 先减4小时得到基准日期时间
        target_time = rounded_time - timedelta(hours=4)
        # URL中的时间再额外减1小时
        url_time = target_time - timedelta(hours=1)
    elif past_or_present == "present":
        target_time = rounded_time
        url_time = target_time
    else:
        raise ValueError("参数仅支持'past'或'present'")
    
    # 提取URL所需的日期时间字段(格式按需调整,确保补零)
    year = target_time.year
    month = str(target_time.month).zfill(2)
    day = str(target_time.day).zfill(2)
    time_part = str(url_time.hour).zfill(2)  # 假设URL时间为小时格式,可改为HH:MM等
    
    # 拼接并发起请求
    url = f"https://awebsite/{year}/{month}/{day}/{time_part}"
    resp = requests.get(url).text
    # 此处可添加响应处理逻辑,如保存结果、日志记录等
    print(f"{past_or_present}模式请求完成,响应内容长度:{len(resp)}")

# 脚本入口
if __name__ == "__main__":
    # 可根据传入的命令行参数选择调用模式,或定时任务分别触发
    get_request("past")
    get_request("present")

定时任务配置

  • Linux/macOS:使用crontab,例如设置每天凌晨2点分别运行两个模式:
    0 2 * * * /usr/bin/python3 /path/to/your/script.py past
    0 2 * * * /usr/bin/python3 /path/to/your/script.py present
    
  • Windows:通过「任务计划程序」创建定时任务,指定Python解释器路径与脚本路径,添加past或present作为参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:05:11