Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Datetime compare with string

Hi

Sorry for the rudimentary questions. When I print a History datetime index I see something like this:

PRINT Security(3766 [IBM]) 2010-12-31 20:30:00+00:00
dtype: object

For back testing and development in general, I want to display a number of prices around a specific datetime, but I don't know how to do a comparison so I can print, i.e.

hiidx = price_history_hi.idxmax()

if hiidx == '2011-01-03 14:31:00+00:00':
print 'Datetime found'

but this comparison does not work. How can I convert the History dataframe's datetime index to a string for comparison?

Thanks in advance

J

1 response

The index is a Timestamp, which you can convert to a datetime and compare to another datetime that you create. For an example, paste the following code into an algorithm, run it with daily data from 2/26/2015 to 2/27/2015, and view the log.

from datetime import datetime  
from pytz import UTC

def initialize(context):  
    context.sec = sid(8554)  
    schedule_function(date_example,  
        date_rule=date_rules.week_end(),  
        time_rule=time_rules.market_close())    

def handle_data(context, data):  
    pass

def date_example(context, data):  
    prices = history(5, '1d', 'price')  
    log.info('Prices: \n{p}'.format(p=prices))  
    dt = datetime(2015, 2, 24, 0, 0, 0, 0, UTC)  
    log.info('dt: {d}'.format(d=dt))  
    max_price_series = prices.idxmax()  # Pandas Series, 1 element  
    log.info('Series: \n{s}'.format(s=max_price_series))  
    max_timestamp = max_price_series[0]  # Pandas Timestamp  
    log.info('Timestamp of max price: {mt}'.format(mt=max_timestamp))  
    max_dt = max_timestamp.to_datetime()  
    if dt == max_dt:  
        log.info('Dates match')  
    else:  
        log.info('Dates do not match')