0

I have function which is generating a time stamp of 10 days at interval of 15mins. These values are stored in a numpy array. I want to apply a condition on each that checks when the time is between 6am and 7pm then print "something" and when its above 7pm to next day till 6am print "something else". my code for time stamp:

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)

I don't know how to grab the date from the timeStamp and compare it chargeTime and dischargeTime.

Vesper
  • 795
  • 1
  • 9
  • 21

2 Answers2

2

This should work. I'm using dt.hour to extract the hour of the datetime object and then np.where() to check for the conditions if it's between 6 and 19, and "something" else (between 19 and 6) "something else". This avoids using for loops and is pretty efficient:

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")

For example:

print(df.loc['2020-01-01 06:45:00':'2020-01-01 07:30:00'])

Output:

                                  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

Finally, if you wish to provide different values for charge_time and discharge_time you can simply define them and use them in the np.where().

charge_time = 6
discharge_time = 19
df['conditions'] = np.where((df['dates'].dt.hour > charge_time) & (df['dates'].dt.hour < discharge_time),"something","something else")
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
1

I think what you want is something like this, where you set the charge_time and discharge_time to integers and compare to the .hour attribute of the timestamp:

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"

which will print the timestamp and then the message like this:

2020-01-09 18:45:00 - something
2020-01-09 19:00:00 - something else
wpercy
  • 9,636
  • 4
  • 33
  • 45