Search code examples
pythonpandastimestampperiod

Pandas is a Timestamp within a Period


I have a timestamp

tstamp = pd.to_datetime('01/11/2017')
tstamp
->> Timestamp('2017-01-11 00:00:00')

and I have a period

per = pd.Period('01/03/2017', 'M')
per
->> Period('2017-01', 'M')

I want to know if my timestamp is within my period. Eg is January 11th 2017 (my tstamp) within the period of January 2017 (my per)

tstamp in per # doesn't work
pd.Series(tstamp).isin([per]) 
->> TypeError: object of type 'pandas._period.Period' has no len()

can't seem to figure it out, and I'd rather NOT do something like:

tstamp < per.to_timestamp()+pd.Timedelta(1,'M') & tstamp > per.to_timestamp()

simply because it doesn't work well with the rest of the time calculations I'm doing on my data.


Solution

  • you can use period.start_time and period.end_time attributes:

    In [134]: per.start_time
    Out[134]: Timestamp('2017-01-01 00:00:00')
    
    In [135]: per.end_time
    Out[135]: Timestamp('2017-01-31 23:59:59.999999999')
    

    Demo:

    In [128]: tstamp = pd.to_datetime(['01/11/2017', '2017-06-01'])
    
    In [129]: tstamp
    Out[129]: DatetimeIndex(['2017-01-11', '2017-06-01'], dtype='datetime64[ns]', freq=None)
    
    In [130]: (per.start_time <= tstamp) & (tstamp <= per.end_time)
    Out[130]: array([ True, False], dtype=bool)