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
In [1]:
# Load library
import pandas as pd
In [2]:
# Create data frame
df = pd.DataFrame()
# Create datetimes
df['date'] = pd.date_range('1/1/2001', periods=100000, freq='H')
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]:
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]: