can pandas handle datetime.datetime subclasses correctly?

Viewed 37

The code snippet below appears to show:

  1. datetime.datetime objects have no nanosecond attribute on construction
  2. when passed into pandas' index.get_loc() they seem to aquire a nanosecond attribute, possibly through conversion into Timestamp
  3. if the object passed into get_loc() is a subclass of datetime however, it does not acquire a nanosecond attribute and the code fails with datetime_sub object has no attribute 'nanosecond'

The error is raised from the conversion from datetime to Timestamp in pandas' datetimes.py. I'm not sure how to look further as the code enters what I imagine to be a C binary at that point. It could be that pandas performs this conversion to Timestamp by checking for datetime as a type in a manner that excludes datetime subtypes.

Questions:

  1. Am I doing this wrong?
  2. Is this a bug in pandas?
  3. Assuming I must use a subclass of datetime, Is there a way to get around this?
import pandas as pd
import datetime from datetime

class datetime_sub(datetime):
    pass

dt = datetime(2012, 10, 22)
dt_s = datetime_sub(2012, 10, 22)

try:
    print(dt.nanosecond)
except Exception as e:
    print (e)

ind = pd.DatetimeIndex(pd.date_range('2012-10-1', '2012-10-30'))
dt_loc = ind.get_loc(dt)
dt_s_loc = ind.get_loc(dt_s)
0 Answers
Related