繁体   English   中英

在 Python 中获取从当前时间到当前时间的(特定)分钟之前的时间值列表

[英]Get a List of Time Values before a (certain) Minutes from the Current time upto the Current Time in Python

我需要定义一个 function 来获取从当前时间前“M”分钟到当前时间(包括当前时间)的 str 时间值的 [list],然后检查是否有任何值与时间值匹配在给定 CSV 文件的时间列中。

我想到了for 循环的想法,但不知道如何添加和 append 列表中的 M 号。 次(绝对初学者的品质)。 因此,我使用以下仅支持M = 1的代码进行了调整:

def Time_Check_Min(M= 1):
    #Check the current system time
    timestr = datetime.now()
    Check_TIMEnow = timestr.strftime("%H:%M")

    #Add 'M' min to Current Time
    Ahead_Time = (timestr + timedelta(minutes=M))
    Check_TIME = Ahead_Time.strftime("%H:%M")

    #Check if the current time is mentioned in the Dataframe
    if Check_TIME in df_.Time.values or Check_TIMEnow in df_.Time.values:
        return True
    else:
        return False

我需要 output 作为 ('%H:%M') 格式的列表,以便检查 CSV 中是否存在它们。 例如,假设当前系统时间为'16:50'且 M = 3,则列表应包含 4 个元素,例如:

['16:47', '16:48', '16:49', '16:50']

另外,由于我使用的是pandas ,因此我想到了使用时间间隔方法。 但同样,我不知道这是否真的有帮助。

我需要改变我的方法吗? 如果是,那么这是最好的方法……如果不是,如何获得该死的清单?

                    !! Thanks for your Time for these Time_Values !!   

不知道你是如何定义你的时间段的,但这将从 25 分钟前开始,并以你需要的格式测试每一分钟。

current_time = datetime.now()
minutes_prior =  25
start_time = current_time + timedelta(minutes=-minutes_prior))
#pd.date_range(start_time, current_time, freq="1min")

def Time_Check_Min(ttest):
    if ttest in df_.Time.values:
        return True
    else:
        return False

for t in pd.date_range(start_time, current_time, freq="1min"):
    print(t.strftime("%H:%M"))
    #Check if the current time is mentioned in the Dataframe
    Time_Check_Min(t.strftime("%H:%M"))

当您使用 pandas 时,我们可以使用 pandas .date_range function 和一些方便的列表切片来做到这一点。

from typing import Optional
import pandas as pd

def get_time_delta_range(time_value : str, M : Optional[int] = 1) -> list:
    t_range = pd.date_range(
                 '01 Jan 2020', '02 Jan 2020',freq='min')\
                 .strftime('%H:%M').tolist()

    idx = t_range.index(time_value)
    return t_range[idx -M : idx + 1]

vals = get_time_delta_range('16:50', M=3)
print(vals)

['16:47', '16:48', '16:49', '16:50']

然后使用isin过滤您的列表。

df_['Time'].isin(vals)

编辑。

def get_time_delta_range(dataframe : pd.DataFrame,
                         time_value : str, M : Optional[int] = 1) -> bool:
    t_range = pd.date_range(
                 '01 Jan 2020', '02 Jan 2020',freq='min')\
                 .strftime('%H:%M').tolist()

    idx = t_range.index(time_value)
    t_range_slice = t_range[idx -M : idx + 1]
    return dataframe.isin(t_range_slice).sum().astype(bool)[0]

df = pd.DataFrame({'time' : ['16:04','16:05']})
get_time_delta_range(df,'16:04')
True

get_time_delta_range(df,'16:09')
False

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM