Suhas RB
Suhas RB

Reputation: 15

Select data between night and day hours

My data looks like this, it is a minute based data for 2 years.

  1. 2017-04-02 00:00:00
  2. 2017-04-02 00:01:00
  3. 2017-04-02 00:02:00
  4. 2017-04-02 00:03:00
  5. 2017-04-02 00:04:00
  6. ....
  7. 2017-04-02 23:59:00
  8. ...
  9. 2019-02-01 22:54:00
  10. 2019-02-01 22:55:00
  11. 2019-02-01 22:56:00
  12. 2019-02-01 22:57:00
  13. 2019-02-01 22:58:00
  14. 2019-02-01 22:59:00
  15. 2019-02-01 23:00:00

I want to access all the data rows between the end of the workday to the beginning of the next. Example between 2018-04-02 18:00:00 2018-04-03 05:00:00 for all the days in my data frame. Please help

Upvotes: 0

Views: 1568

Answers (2)

ALollz
ALollz

Reputation: 59549

If you use a DatetimeIndex then you can use .between_time

import pandas as pd
df = pd.DataFrame({'date': pd.date_range('2017-04-02', freq='90min', periods=100)})
df = df.set_index('date')

df.between_time('18:00', '5:00')

#date
#2017-04-02 00:00:00
#2017-04-02 01:30:00
#2017-04-02 03:00:00
#2017-04-02 04:30:00
#2017-04-02 18:00:00
#2017-04-02 19:30:00
#2017-04-02 21:00:00
#2017-04-02 22:30:00
#....

Upvotes: 2

Peter Leimbigler
Peter Leimbigler

Reputation: 11105

One approach is boolean indexing based on conditions on the datetime column or index. Assuming your DataFrame is named df and it has a DatetimeIndex equal to the example data you've posted, try this:

df[(df.index.hour >= 18) | (df.index.hour <= 5)]

Upvotes: 1

Related Questions