pandas-dev / pandas

Flexible and powerful data analysis / manipulation library for Python, providing labeled data structures similar to R data.frame objects, statistical functions, and much more
https://pandas.pydata.org
BSD 3-Clause "New" or "Revised" License
43.24k stars 17.79k forks source link

Convenience function for timeseries #1563

Closed changhiskhan closed 12 years ago

changhiskhan commented 12 years ago

from pydata mailing list:

just wondering if there is a more convenient way to convert the new Period / PeriodIndex classes to datetime objects. As well as converting into lists of tuples to insert into sql databases.

For example:

import pandas as pd

prng = pd.period_range('2012-01', periods = 12, freq = 'M') prd = pd.Period.now('B') ts = pd.Series(range(12), index = prng)

could we have a shortcut to_pydatetime method on the Period class?

dt = prd.to_timestamp().to_pydatetime() # pandas 0.8 way

desired: dt = prd.to_pydatetime()

ditto for PeriodIndex

dtrng = prng.to_timestamp().to_pydatetime() # pandas 0.8 way

desired: dtrng = prng.to_pydatetime()

converting time series to list of (datetime, value) tuples for inserting into

sql database. This is what .tolist() returned in the old scikits.timeseries

module

sql_tuples = zip(ts.index.to_timestamp().to_pydatetime(), ts.tolist()) # pandas 0.8 way

desired: sql_tuples = ts.tolist() # or ts.to_sqltuples(), etc

mattknoxca commented 12 years ago

Based on Wes' comment that Timestamp is in fact a subclass of datetime (which I wasn't aware of when I wrote the original post), this is no longer necessary from my point of view. The results of .to_timestamp can be used everywhere that I thought I needed datetime objects.

And the sql_tuples expression can be simplified to:

sql_tuples = zip(ts.index.to_timestamp(), ts)

Which is also a lot simpler than my original expression. It might be nice to have something more generally that creates a list of tuples for Series or DataFrame objects which includes the index as the first column. That would seem like the natural representation for exporting to sql in my mind. But that is a separate issue.