Python 如何在date_range函数生成的datetime中应用条件?
我有一个函数,它每隔15分钟生成一个10天的时间戳。这些值存储在numpy数组中。我想对每一个应用一个条件,检查时间在早上6点到晚上7点之间,然后打印“某物”,当时间在晚上7点以上到第二天早上6点,打印“其他某物”。 我的时间戳代码:Python 如何在date_range函数生成的datetime中应用条件?,python,python-3.x,pandas,python-datetime,Python,Python 3.x,Pandas,Python Datetime,我有一个函数,它每隔15分钟生成一个10天的时间戳。这些值存储在numpy数组中。我想对每一个应用一个条件,检查时间在早上6点到晚上7点之间,然后打印“某物”,当时间在晚上7点以上到第二天早上6点,打印“其他某物”。 我的时间戳代码: import pandas as pd import numpy as np timeStamp = pd.date_range(start='1/1/2020', end='1/10/2020', freq='15min') chargeTime = datet
import pandas as pd
import numpy as np
timeStamp = pd.date_range(start='1/1/2020', end='1/10/2020', freq='15min')
chargeTime = datetime.time(6,0,0)
dischargeTime = datetime.time(19,0,0)
我不知道如何从时间戳中获取日期,并将其与chargeTime和dischargeTime进行比较 我认为您想要的是这样的,您将
充电时间
和放电时间
设置为整数,并与时间戳的小时
属性进行比较:
import pandas as pd
import numpy as np
time_stamps = pd.date_range(start='1/1/2020', end='1/10/2020', freq='15min')
charge_time = 6 # 6am
discharge_time = 19 # 7pm
for t in time_stamps:
if charge_time <= t.hour < discharge_time:
print str(t) + " - something"
else:
print str(t) + " - something else"
我想你想要的是这样的东西,你将
充电时间
和放电时间
设置为整数,并与时间戳的小时
属性进行比较:
import pandas as pd
import numpy as np
time_stamps = pd.date_range(start='1/1/2020', end='1/10/2020', freq='15min')
charge_time = 6 # 6am
discharge_time = 19 # 7pm
for t in time_stamps:
if charge_time <= t.hour < discharge_time:
print str(t) + " - something"
else:
print str(t) + " - something else"
这应该行得通。我使用
dt.hour
提取datetime对象的hour,然后np.where()
检查条件是否介于6和19之间,以及“something”(介于19和6之间)“something other”。这避免了对循环使用,并且非常有效:
timeStamp = pd.date_range(start='1/1/2020', end='1/10/2020', freq='15min')
df = timeStamp.to_frame()
df.columns = ['dates']
df['conditions'] = np.where((df['dates'].dt.hour > 6) & (df['dates'].dt.hour < 19),"something","something else")
输出:
dates conditions
2020-01-01 06:45:00 2020-01-01 06:45:00 something else
2020-01-01 07:00:00 2020-01-01 07:00:00 something
2020-01-01 07:15:00 2020-01-01 07:15:00 something
2020-01-01 07:30:00 2020-01-01 07:30:00 something
最后,如果您希望为充电时间
和放电时间
提供不同的值,您可以简单地定义它们并在np.where()中使用它们
充电时间=6
出院时间=19
df['conditions']=np.其中((df['dates'].dt.hour>充电时间)和(df['dates'].dt.hour<放电时间),“某物”,“某物”)
这应该行得通。我使用dt.hour
提取datetime对象的hour,然后np.where()
检查条件是否介于6和19之间,以及“something”(介于19和6之间)“something other”。这避免了对
循环使用,并且非常有效:
timeStamp = pd.date_range(start='1/1/2020', end='1/10/2020', freq='15min')
df = timeStamp.to_frame()
df.columns = ['dates']
df['conditions'] = np.where((df['dates'].dt.hour > 6) & (df['dates'].dt.hour < 19),"something","something else")
输出:
dates conditions
2020-01-01 06:45:00 2020-01-01 06:45:00 something else
2020-01-01 07:00:00 2020-01-01 07:00:00 something
2020-01-01 07:15:00 2020-01-01 07:15:00 something
2020-01-01 07:30:00 2020-01-01 07:30:00 something
最后,如果您希望为充电时间
和放电时间
提供不同的值,您可以简单地定义它们并在np.where()中使用它们
充电时间=6
出院时间=19
df['conditions']=np.其中((df['dates'].dt.hour>充电时间)和(df['dates'].dt.hour<放电时间),“某物”,“某物”)