Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a `pandas.tslib.Timestamp` object to `datetime`

Tags:

python

pandas

I am trying to convert a pandas.tslib.Timestamp object to datetime.df['orig_iss_dt'] is the pandas.tslib.Timestamp object. I used the answer here to try and do this, but find that print(type(origination)) still returns the same type.

df['orig_iss_dt'] = df['orig_iss_dt'].apply(lambda x: datetime.date(x.year,x.month,x.day)) 

for (i, row) in df:
    origination = row.orig_iss_dt
    print(type(origination))
like image 720
Jojo Avatar asked Dec 14 '22 12:12

Jojo


1 Answers

The easiest way to convert a pandas Timestamp to datetime.datetime is to use the to_pydatetime method. This can be called on Timestamp directly or on the series:

In [15]: s = pd.Series(pd.date_range('2012-01-01', periods=3))

In [16]: s
Out[16]:
0   2012-01-01
1   2012-01-02
2   2012-01-03
dtype: datetime64[ns]

In [17]: s[0]
Out[17]: Timestamp('2012-01-01 00:00:00')

In [18]: s.dt.to_pydatetime()
Out[18]:
array([datetime.datetime(2012, 1, 1, 0, 0),
       datetime.datetime(2012, 1, 2, 0, 0),
       datetime.datetime(2012, 1, 3, 0, 0)], dtype=object)

But note that this is often times not needed, as Timestamp is a subclass of datetime.datetime.

like image 74
joris Avatar answered Feb 11 '23 12:02

joris