python 如何过滤包含特定时间的日期和时间的pandas dataframe列?

qhhrdooz  于 2023-06-04  发布在  Python
关注(0)|答案(1)|浏览(176)

Pandas dataframe日期和时间过滤
嘿,团队!脚本的整个想法是在指定的时间访问链接[“20:00”,“20:30”,“22:15”,“22:45”,“23:30”,“00:00”,“01:45”,“02:30”,“03:00”,“03:30”],并按照脚本运行的时间+ 1小时过滤列Expected Ship Date。
示例:脚本在04/06/2023 23:30运行,它将在05/06/2023 00:30之前过滤预期发货日期
目前,它似乎不能正常工作,无论什么原因,无论我运行它的时间,它返回当前一天21:00。
你知道我错过了什么吗

__author__ = "studorie"
__version__ = "1.0.1"

from datetime import datetime, timedelta
from io import StringIO

import pandas as pd
from apscheduler.schedulers.blocking import BlockingScheduler

from function.requests_retryer import requests_retry_session

def roster(fc):
    url = (
        f"https://link.com/{fc}"
        )

    with requests_retry_session() as request:
        response = request.get(url)

    if response.status_code != 200:
        print(response.raise_for_status())

    df = pd.read_csv(StringIO(response.text), sep=",")
    df.drop(['FN SKU', 'Scannable ID', 'Condition', 'Ship Method', 'Ship Option', 'Pick Priority'], axis=1,
            inplace=True)

    df["Expected Ship Date"] = pd.to_datetime(df["Expected Ship Date"])

    # Get today's date
    today = datetime.now().date()

    # Get the current time
    current_time = datetime.now().time()

    # Find the index of the next job time
    job_index = next(
        (i for i, job_time in enumerate(job_times) if datetime.strptime(job_time, "%H:%M").time() > current_time), 0)

    # Get the adjusted job time
    adjusted_job_time = job_times[job_index]

    # Calculate the adjusted expected ship date based on the scheduled job time + 1 hour
    if adjusted_job_time == "00:00":
        # If the adjusted job time is midnight, add 1 day instead of 1 hour
        adjusted_date = today + timedelta(days=1)
    else:
        adjusted_date = today

    adjusted_datetime = datetime.combine(adjusted_date,
                                         datetime.strptime(adjusted_job_time, "%H:%M").time()) + timedelta(hours=1)
    adjusted_expected_ship_date = adjusted_datetime.strftime("%d/%m/%Y %H:%M")

    # Filter the DataFrame based on the adjusted expected ship date
    filter_condition = df["Expected Ship Date"].dt.strftime("%d/%m/%Y %H:%M") == adjusted_expected_ship_date
    filtered_df = df[filter_condition]

    timestamp = datetime.now().strftime("%d-%m-%Y-%H-%M")
    filename = f"Y:/Public/L&D/Reports for ops/Flow risk/Pick_SLA_{timestamp}.csv"

    # Save the filtered data to the specified filename
    filtered_df.to_csv(filename, index=False)
    print(f"Filtered data saved to {filename}")

if __name__ == "__main__":
    schedule = BlockingScheduler()
    job_times = ["20:00", "20:30", "22:15", "22:45", "23:30", "00:00", "01:45", "02:30", "03:00", "03:30"]
    for job_time in job_times:
        schedule.add_job(roster, 'cron', timezone="Europe/London", hour=int(job_time.split(':')[0]),
                         minute=int(job_time.split(':')[1]), args=["EMA2"])
    schedule.start()
5ktev3wc

5ktev3wc1#

在函数roster(fc)中,

# Find the index of the next job time
    job_index = next(
        (i for i, job_time in enumerate(job_times) if datetime.strptime(job_time, "%H:%M").time() > current_time), 0)

每次运行roster都会创建一个新的迭代器,然后获取第一个datetime 20:00并返回21:00

(i for i, job_time in enumerate(job_times) if datetime.strptime(job_time, "%H:%M").time() > current_time)

您应该在roster运行之前创建一个迭代器,

if __name__ == "__main__":
    schedule = BlockingScheduler()
    job_times = ["20:00", "20:30", "22:15", "22:45", "23:30", "00:00", "01:45", "02:30", "03:00", "03:30"]
    
    date_iter = (i for i, job_time in enumerate(job_times)
                if datetime.strptime(job_time, "%H:%M").time() > current_time)
    
    for job_time in job_times:
        schedule.add_job(roster, 'cron', timezone="Europe/London", hour=int(job_time.split(':')[0]),
                         minute=int(job_time.split(':')[1]), args=["EMA2"])
    schedule.start()

rosterdate_iter获取元素

def roster(fc):
    ...
    # Find the index of the next job time
    job_index = next(date_iter, 0)
    ...

相关问题