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

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

问题描述

我使用 pandas.to_datetime 来解析我的数据中的日期.Pandas 默认用 datetime64[ns] 表示日期,即使这些日期都是每天.我想知道是否有一种优雅/聪明的方式将日期转换为 datetime.datedatetime64[D] 这样,当我将数据写入 CSV 时,日期没有附加 00:00:00.我知道我可以逐个元素地手动转换类型:

I use pandas.to_datetime to parse the dates in my data. Pandas by default represents 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?

推荐答案

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

上面返回一个 datetime.date dtype,如果你想要一个 datetime64 那么你可以 normalize午夜,因此它将所有值设置为 00:00:00:

The above returns a datetime.date dtype, if you want to have a datetime64 then you can just normalize the time component to midnight so it sets all the values to 00:00:00:

df['normalised_date'] = df['dates'].dt.normalize()

这将 dtype 保持为 datetime64,但显示仅显示 date 值.

This keeps the dtype as datetime64, but the display shows just the date value.

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

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