使用pandas.to_datetime时,只保留日期部分 [英] Keep only date part when using pandas.to_datetime

查看:3772
本文介绍了使用pandas.to_datetime时,只保留日期部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用pandas.to_datetime解析数据中的日期。熊猫默认情况下表示datetime64 [ns]的日期,即使日期都是每天。
我不知道是否有一个优雅/聪明的方式将日期转换为datetime.date或datetime64 [D],以便在将数据写入csv时,日期不会附加00:00:00。我知道我可以手动转换类型的元素:

I am using pandas.to_datetime to parse the dates in my data. Pandas by default represent the dates with datetime64[ns] even though the dates are all daily only. I wonder whether there is an elegant/clever way to convert the dates to datetime.date or datetime64[D] so that when I write the data to csv, the dates are not appended with 00:00:00. I know I can convert the type manually element-by-element:

[dt.to_datetime().date() for dt in df.dates]

但是这是非常慢的,因为我有很多行,它有点失败使用pandas.to_datetime的目的。有没有办法一次转换整个列的dtype?或者,pandas.to_datetime是否支持精度规范,以便在处理日常数据时摆脱时间部分?

But this is really slow since I have many rows and it sort of defeats the purpose of using pandas.to_datetime. Is there a way to convert the dtype of the entire column at once? Or alternatively, does pandas.to_datetime support a precision specification so that I can get rid of the time part while working with daily data?

推荐答案

p>由于版本 0.15.0 现在可以使用 .dt 仅访问日期组件:

Since version 0.15.0 this can now be easily done using .dt to access just the date component:

df['just_date'] = df['dates'].dt.date

这篇关于使用pandas.to_datetime时,只保留日期部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆