Title: Select Date And Time Ranges
Slug: select_date_and_time_ranges
Summary: How to select date and time ranges in Python.
Date: 2017-09-11 12:00
Category: Machine Learning
Tags: Preprocessing Dates And Times
Authors: Chris Albon

Preliminaries


In [1]:
# Load library
import pandas as pd

Create pandas Series Time Data


In [2]:
# Create data frame
df = pd.DataFrame()

# Create datetimes
df['date'] = pd.date_range('1/1/2001', periods=100000, freq='H')

Select Time Range (Method 1)

Use this method if your data frame is not indexed by time.


In [3]:
# Select observations between two datetimes
df[(df['date'] > '2002-1-1 01:00:00') & (df['date'] <= '2002-1-1 04:00:00')]


Out[3]:
date
8762 2002-01-01 02:00:00
8763 2002-01-01 03:00:00
8764 2002-01-01 04:00:00

Select Time Range (Method 2)

Use this method if your data frame is indexed by time.


In [4]:
# Set index
df = df.set_index(df['date'])

# Select observations between two datetimes
df.loc['2002-1-1 01:00:00':'2002-1-1 04:00:00']


Out[4]:
date
date
2002-01-01 01:00:00 2002-01-01 01:00:00
2002-01-01 02:00:00 2002-01-01 02:00:00
2002-01-01 03:00:00 2002-01-01 03:00:00
2002-01-01 04:00:00 2002-01-01 04:00:00