Search code examples
pythonextractsampletimetable

extract data in specific interval


I have one table with two columns: date (01-01-2010 to 31-08-2021), value (mm) I would like to get only data during 2020. There is a function or similar to get some only data in specific period?

For example to create one pivot.


Solution

  • try this:

    
    df = pd.DataFrame(
        {'date':['27-02-2010','31-1-2020','31-1-2021','02-1-2020','13-2-2020',
                 '07-2-2019','30-4-2018','04-8-2020','06-4-2013','21-6-2020'],
         'value':['foo','bar','lorem','ipsum','alpha','omega','big','small','salt','pepper']})
    
    df[pd.to_datetime(df['date']).dt.year == 2020]
    

    Output:

        date    value
    1   31-1-2020   bar
    3   02-1-2020   ipsum
    4   13-2-2020   alpha
    7   04-8-2020   small
    9   21-6-2020   pepper
    

    Or for serching with any range you can use this:

    df['date'] = pd.to_datetime(df['date'])
    df[(df['date']>pd.Timestamp(2020,1,1)) & (df['date']<pd.Timestamp(2020,12,31))]