Search code examples
pythonpandastimestampperiod

Check if a pandas.Timestamp is in a pandas.Period


# pseudo code: 
myPeriod.contains(myTimestamp)

I found the lack of such function in pandas quite surprising. Am I missing something here?


Solution

  • You can try isin if you have multiple values:

    print df.index
    PeriodIndex(['2015-11'], dtype='int64', name=u'', freq='M')
    
    d = "2015-09-01"
    d1 = "2015-10-01"
    print df.index.isin([pd.to_datetime(d).to_period('M'), pd.to_datetime(d1).to_period('M')])
    [False]
    
    d = "2015-11-01"
    d1 = "2015-11-01"   
    print df.index.isin([pd.to_datetime(d).to_period('M'), pd.to_datetime(d1).to_period('M')])
    [ True]
    

    If you want compare only one datetime, easier is use (thanks maxymoo):

    d = "2015-09-01"    
    print df.index == pd.to_datetime(d).to_period('M')  
    [False]
    
    d = "2015-11-01"    
    print df.index == pd.to_datetime(d).to_period('M')  
    [True]  
    

    Or with Series:

    print df.a
    0   2015-11
    Name: a, dtype: object
    
    d = "2015-09-01"
    d1 = "2015-10-01"   
    print df.a.isin([pd.to_datetime(d).to_period('M'), pd.to_datetime(d1).to_period('M')]).values
    [False]
    
    d = "2015-11-01"
    d1 = "2015-11-01"
    print df.a.isin([pd.to_datetime(d).to_period('M'), pd.to_datetime(d1).to_period('M')]).values
    [ True]