[英]How to assign time objects to bins?
我有一個需要分配給時間窗口(7、9、12、15、18)的時間列表,以確保每個時間窗口都被我的列表中的一個元素覆蓋。
from datetime import date, time, datetime
def nearest(items, target):
return min(items, key=lambda x: abs(x - target))
time_list = [datetime.datetime(2019, 12, 17, 7, 30),
datetime.datetime(2019, 12, 17, 9, 0),
datetime.datetime(2019, 12, 17, 16, 0),
datetime.datetime(2019, 12, 17, 18, 30),
datetime.datetime(2019, 12, 17, 21, 30),
datetime.datetime(2019, 12, 17, 12, 30),
datetime.datetime(2019, 12, 17, 19, 0),
datetime.datetime(2019, 12, 17, 0, 0),
datetime.datetime(2019, 12, 17, 14, 30)]
target_times = [datetime.combine(date.today(),time(i,0)) for i in range(6,19,3)]
coverage = [abs(nearest(time_list, t)-t)<time(1,30) for t in target_times]
期望的輸出:
[True, True, True, True, True]
這當前返回一個“<”錯誤,我可以解決這個錯誤,但我不確定這是否是完成我想做的事情的最佳方式。 我有可用的 numpy 和 scipy 庫,可能還有其他庫。
這是我根據這個 SO question How to check the current time is in range in python組合在一起的解決方案? . 它有效,但我想知道是否有更好的解決方案。
def time_in_range(start, end, x):
today = timezone.localtime().date()
start = timezone.make_aware(datetime.combine(today, start))
end = timezone.make_aware(datetime.combine(today, end))
x = timezone.make_aware(datetime.combine(today, x))
if end <= start:
end += timedelta(days=1) # tomorrow!
if x <= start:
x += timedelta(days=1) # tomorrow!
return start <= x <= end
downloaded = [False, False, False, False, False]
times = [time(i,0) for i in [5,8,10,13,16,20]]
for i in range(5):
for start_time in start_times:
if time_in_range(times[i], times[i+1], start_time):
downloaded[i] = True
您的直接問題的答案是您正在嘗試將timedelta
ob 對象與time
對象進行比較。 在這種情況下,您可能希望創建一個timedelta
對象,如下所示:
timedelta(hours=1, minutes=30)
代替
time(1,30)
你可能希望在這里使用熊貓; 因為它具有處理 bin 和 interval 的內置方法。
在這種情況下,您有四 (4) 個時間間隔:
“[”表示包含,而“)”表示不包含。
您可以將time_list
加載到time_list
數據幀中:
import pandas as pd
df = pd.DataFrame(time_list,columns=['timestamp']) # `columns` is how you name the column(s)
然后,我建議 pandas 的原因是它有一個名為.cut()
的有用函數,它可以對值進行分類。
>>> bins = [7, 9, 12, 15, 18]
>>> pd.cut(df['timestamp'].dt.hour,bins=bins).unique().dropna().sort_values()
[(7, 9], (9, 12], (12, 15], (15, 18]]
然后,您可以像這樣測試上述操作的結果的適當長度(減 1 是因為有五個 bin:
>>> covered_intervals = _ # an underscore gets the most recent value in the interpreter
>>> len(covered_intervals) == len(bins) - 1
True
如果你想要一個布爾值列表,你可以這樣做:
result = []
for i in covered_intervals:
if i.left in bins:
result.append(True)
else:
result.append(False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.