How can I extract data from date range in time & date format?

Question:

I have a date set for a couple of years and I am trying to extract data from a specific range and time, but I cannot get it to work with Pandas. I am sure there is something wrong with the date & time format, but oddly I can get hourly averages but cannot extract a date & time range.

This is the code, but it never return any data, I know it there is data in that time period. I think the date & time format is correct, but not sure why it does not work.

Code

import pandas as pd

import numpy as np

df = pd.DataFrame([['2018-01-01 16:00:00+00:00', 2], ['2018-01- 
01 17:00:00+00:00', 3], ['2018-01-01 18:00:00+00:00', 6]['2018- 
01-01 19:00:00+00:00', 9]], columns=['time', 'data'])

print(df.head)

df['time'] = pd.to_datetime(df['time']) 

df2018 = df.loc['2018-01-01 16:30:00':'2018-01-01 18:00:00']

print(df2018.head)
Asked By: Brendon

||

Answers:

Is the time column your index? if not, make it your index:

pd.set_index(df['time'])

Then:

df["2018-10-02":"2018-10-03"] # slicing a date period

df.loc[(df['time'] > start_date) & (df['time'] <= end_date )] 
Answered By: user17431226
# Inorder to make time the index 
pd.set_index(df['time']) returns an error

# to make time the index, I used
df.set_index(['time'])

#To slice a date period  this is what works for me

from datetime import datetime

df2018 = df.loc[(df['time'] >= '2018-01-01 16:30:00' ) & (df['time'] <= '2018-01-01 18:00:00')] 
Answered By: Duff
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.