Search code examples
pythonpandasstdin

how to slice dates from a dataframe using standard input function?


I saw the documentation in the Indexing and selecting data which involves hardcore scripting method to slice a range of data from a dataframe.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('d1.csv')

df['time']=pd.to_datetime(df['time'], unit='ns')

df = df.drop('name', 1)

df['Time'] = df['time'].dt.time

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

df = df.set_index(['date'])

df= df.loc['2018-07-04':'2018-07-05']

But I need to select a range of data from standard input function, How it can be done:

Rather than using df= df.loc['2018-07-04':'2018-07-05']say in the form at the console it will be asked to Enter the start date : and Enter the stop date : and by doing so I will get the data of the selected date ranges only.

I actually tried it doing as:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('d1.csv')

df['time']=pd.to_datetime(df['time'], unit='ns')

df = df.drop('name', 1)

df['Time'] = df['time'].dt.time

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

df = df.set_index(['date'])
Starting_Date = input(" Please Enter the Starting_Date : ")
Ending_Date = input(" Please Enter the Ending_Date : ")

data = df[Starting_Date:Ending_Date]

But this doesn't work...kindly have a look upon it.


Solution

  • Please try this. The date is in format year-month-day for example '2018-08-16'.

    from datetime import datetime
    
    a = input('Starting_Date: ')
    b = input('Ending_Date :')
    
    starting_date = datetime.strptime(a, "%Y-%m-%d").date()
    ending_date = datetime.strptime(b, "%Y-%m-%d").date()
    
    df.loc[starting_date:ending_date]
    

    Hope that works for you :)