0

The following is my code which i am running on a dataframe

def get_day_limit(self):
    self.df['day_end'] = np.where(self.df.index == self.df.index.get_loc(dt.strptime(str(self.df.index.date),'%Y-%m-%d')+' '+'15:15:00'),1,0)

The index date and time format is as follows

2020-02-18 09:15:00

2020-02-18 09:30:00

2020-02-18 09:45:00

When the time is equal to 15:15:00 irrespective of the date, i want the self.df['day_end'] to be 1 else 0

but i get the following error:-

> ValueError: time data '[datetime.date(2020, 2, 18) datetime.date(2020,
> 2, 18)\n datetime.date(2020, 2, 18) ... datetime.date(2020, 5, 20)\n
> datetime.date(2020, 5, 20) datetime.date(2020, 5, 20)]' does not match
> format '%Y-%m-%d'

When i had tried it separately, i noticed that the 0 is removed from the month datetime.date because of which it is unable to read month with %m

i search stack overflow and found that, when we use %Y-%m-%d format with a hyphen, it removes the zero in the start. Here Python strftime - date without leading 0?.

BUT MY DATA WILL ONLY BE AVAILABLE WITH HYPHEN.

i tried using .date() but ndarray is non callable object

roganjosh
  • 12,594
  • 4
  • 29
  • 46
Kunthu Dhadda
  • 25
  • 1
  • 6

2 Answers2

1

In your case, you can just use time to extract the time and compare:

# NOT the common `from datetime import datetime`
import datetime

def get_day_limit(self):
    self.df['day_end'] = (self.df.index.time == datetime.time(15,15)).astype(int)

Or another way without extra package:

def get_day_limit(self):
    time = self.df.index - self.df.index.normalize()
    self.def['day_end'] = (time==pd.to_timedelta('15:15:00')).astype(int)
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
  • This gave me the following error TypeError: descriptor 'time' requires a 'datetime.datetime' object but received a 'int' – Kunthu Dhadda May 25 '20 at 15:40
  • @KunthuDhadda try the second approach, or my comment under the other answer. – Quang Hoang May 25 '20 at 15:41
  • and also, it's just `import datetime`, not `from datetime import datetime`. They are two different things. – Quang Hoang May 25 '20 at 15:42
  • @KunthuDhadda: QuangHoang's solution works fine for me, your issue seems to be related to df.index. make sure it is dtype='datetime64[ns]' when you call the method in your class – FObersteiner May 25 '20 at 15:55
0

try this

def get_day_limit(df):
    if (df.index.hour==15) & (df.index.minute==15):
       df['day_end'] = 1
    else:
       df['day_end'] = 0

David Serero
  • 144
  • 9