从 pandas 的date& time变量中删除时间? [英] removing time from date&time variable in pandas?

查看:69
本文介绍了从 pandas 的date& time变量中删除时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,该变量包含30万条带有日期的记录,日期看起来像
2015-02-21 12:08:51
从那一天起,我要删除时间

i have a variable consisting of 300k records with dates and the date look like
2015-02-21 12:08:51
from that date i want to remove time

日期变量的类型是pandas.core.series.series

type of date variable is pandas.core.series.series

这是我尝试的方式

from datetime import datetime,date
date_str = textdata['vfreceiveddate']  
format_string = "%Y-%m-%d"
then = datetime.strftime(date_str,format_string)   

一些随机错误

在上面的代码中,textdata是我的数据集名称,而vfreceived date是一个由日期组成的变量.
我该如何编写代码以从日期时间中删除时间.

In the above code textdata is my datasetname and vfreceived date is a variable consisting of dates
How can i write the code to remove the time from the datetime.

推荐答案

假定所有日期时间字符串都采用类似的格式,然后使用

Assuming all your datetime strings are in a similar format then just convert them to datetime using to_datetime and then call the dt.date attribute to get just the date portion:

In [37]:

df = pd.DataFrame({'date':['2015-02-21 12:08:51']})
df
Out[37]:
                  date
0  2015-02-21 12:08:51
In [39]:

df['date'] = pd.to_datetime(df['date']).dt.date
df
Out[39]:
         date
0  2015-02-21

编辑

如果只想更改显示而不是dtype,则可以调用dt.normalize:

In[10]:
df['date'] = pd.to_datetime(df['date']).dt.normalize()
df

Out[10]: 
        date
0 2015-02-21

您可以看到dtype仍为datetime:

You can see that the dtype remains as datetime:

In[11]:
df.dtypes

Out[11]: 
date    datetime64[ns]
dtype: object

这篇关于从 pandas 的date& time变量中删除时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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