Convert Pandas DateTimeIndex to Integer YYYYMMDD?

Is there a preferred way to convert pandas DateTimeIndex to YYYYMMDD integer column? I need the YYYYMMDD integer format for the old store back to a pre-existing SQLite table that assumes the dates are integers.

Pandas' to_sql () does not work with sqlite3.InterfaceError when using SQLite flavor and index = True. Obviously using the flavor of SQLalchemy can convert the DateTimeIndex to a string, but again I need this as an integer YYYYMMDD.

Even though the to_datetime () and to_pydatetime () functions do not seem to have a from_datetime () function .

+3


source to share


1 answer


I am confused about what you want. You are trying to convert the format DateTimeIndex

to YYYYMMDD

; why do you need a method from_datetime

?

Anyway, you can either display / translate a Pandas function Timestamp.strftime

over it, or use that function to_pydatetime

you found and then map the Python function datetime.strftime

over the resulting array.

Apparently using the flavor of SQLalchemy can convert the DateTimeIndex to a string, but again I need this to be an integer YYYYMMDD.

It's easy. For a string YYYYMMDD

to convert it to an integer, you just call int

on it - or if it's in a Pandas / Numpy array, you display or cast int

over it, or even more, just enter your dtype.



For example:

>>> dti = pd.DatetimeIndex(['2014-08-31', '2014-09-01'])
>>> pdt = dti.to_pydatetime()
>>> sdt = np.vectorize(lambda s: s.strftime('%Y%m%d'))(pdt)
>>> idt = sdt.astype('I4')
>>> idt
array([20140831, 20140901], dtype=uint32)

      

(I am not suggesting that this is the most efficient or most readable way to convert DateTimeIndex

to an array of integers YYYYMMDD

, just so that it works with functions you already know about, and if that's not what you want, your question is meaningless.)

+1


source







All Articles