Series.astype将所有类似日期的对象转换为datetime64 [ns].
要转换为datetime64 [D],请在调用astype之前使用值来获取NumPy数组:
dates_input = df["month_15"].values.astype('datetime64[D]')
请注意,NDFrame(例如Series和DataFrames)只能将类似日期时间的对象保存为dtype datetime64 [ns]的对象.将所有日期时间自动转换为常见的dtype简化了后续日期计算.但它使得无法在DataFrame列中存储datetime64 [s]对象. Pandas核心开发人员,Jeff Reback explains,
“We don’t allow direct conversions because its simply too complicated to keep anything other than datetime64[ns] internally (nor necessary at all).”
另请注意,即使df [‘month_15’].astype(‘datetime64 [D]’)有dtype datetime64 [ns]:
In [29]: df['month_15'].astype('datetime64[D]').dtype
Out[29]: dtype('
当你遍历系列中的项目时,你会得到pandas时间戳,而不是datetime64 [ns].
In [28]: df['month_15'].astype('datetime64[D]').tolist()
Out[28]: [Timestamp('2010-01-15 00:00:00'), Timestamp('2011-01-15 00:00:00&