[英]Convert Pandas DateTimeIndex to YYYYMMDD integer?
Is there a preferred way to convert a pandas DateTimeIndex to a column of YYYYMMDD integers? 有没有将pandas DateTimeIndex转换为YYYYMMDD整数列的首选方法? I need the YYYYMMDD integer format for legacy storage back into a pre-existing SQLite table that assumes dates are integers.
我需要将旧存储的YYYYMMDD整数格式返回到预先存在的SQLite表中,该表假设日期是整数。
Pandas' to_sql() fails with an 'sqlite3.InterfaceError' when using the SQLite flavour and index=True. 当使用SQLite flavor并且index = True时,Pandas的to_sql()失败并带有'sqlite3.InterfaceError'。 Apparently using an SQLalchemy flavor can convert the DateTimeIndex to string, but again I need to have this as an YYYYMMDD integer.
显然使用SQLalchemy风格可以将DateTimeIndex转换为字符串,但我需要再次将其作为YYYYMMDD整数。
While there seems to be to_datetime() and to_pydatetime() functions, there doesn't seem to be a from_datetime() function. 虽然似乎有to_datetime()和to_pydatetime()函数,但似乎没有from_datetime()函数。
I'm confused by what you want. 我对你想要的东西感到困惑。 You're trying to convert a
DateTimeIndex
to YYYYMMDD
format; 您正在尝试将
DateTimeIndex
转换为 YYYYMMDD
格式; why would you need a from_datetime
method to do that? 为什么你需要一个
from_datetime
方法呢?
Anyway, you can either map/broadcast the Pandas Timestamp.strftime
function over it, or use that to_pydatetime
function that you found and then map the Python datetime.strftime
function over the resulting array. 无论如何,您可以在其上映射/广播Pandas
Timestamp.strftime
函数,或者使用您找到的to_pydatetime
函数,然后在生成的数组上映射Python datetime.strftime
函数。
Apparently using an SQLalchemy flavor can convert the DateTimeIndex to string, but again I need to have this as an YYYYMMDD integer.
显然使用SQLalchemy风格可以将DateTimeIndex转换为字符串,但我需要再次将其作为YYYYMMDD整数。
That's easy. 这很容易。 Given a
YYYYMMDD
string, to convert that to an integer, you just call int
on it—or, if it's in a Pandas/Numpy array, you map or broadcast int
over it, or, even more simply, just cast its dtype. 给定一个
YYYYMMDD
字符串,要将其转换为整数,只需在其上调用int
或者,如果它在Pandas / Numpy数组中,则在其上映射或广播int
,或者更简单地说,只是转换它的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'm not suggesting that this is the most efficient or most readable way to convert a DateTimeIndex
to an array of YYYYMMDD
integers, just that it's doable with the functions you appear to already know about, and if this isn't what you want, your question doesn't make sense.) (我并不是说这是将
DateTimeIndex
转换为YYYYMMDD
整数数组的最有效或最可读的方法,只是它可以用你看来已经知道的函数来实现,如果这不是你想要的,你的问题没有意义。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.