pandas 将时间戳列转换为日期时间 [英] Pandas Convert Timestamp Column to Datetime

查看:262
本文介绍了 pandas 将时间戳列转换为日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下数据框架和必要的争吵:

 将pandas导入pd 
df = pd.DataFrame {'A':['a','b','c'],
'dates':['2015-08-31 00:00:00','2015-08-24 00:00 :00','2015-08-25 00:00:00']})
df.dates = df.dates.astype(str)
df ['dates'] = pd.to_datetime( df.dates.str.split(',\s *')str [0])
set(df ['dates'])

我结束了:

  {Timestamp('2015-08 -24 00:00:00'),
时间戳('2015-08-25 00:00:00'),
时间戳('2015-08-31 00:00:00')}

我需要将时间戳转换回datetime(真正的,只是日期)的格式。 >

我已经根据这篇文章

  df ['dates'] to_pydatetime()

但是返回:

  AttributeError:'Series'对象没有属性'to_pydatetime'

在我的实际数据中,数据类型为:< M8 [ns]



提前感谢

解决方案

请使用 dt.date 返回一个 datetime.date 对象:

 在[3]中:
set(df ['dates']。dt.date)

输出[3]:
{datetime.date ,8,24),
datetime.date(2015,8,25),
datetime.date(2015,8,31)}


Given the following data frame and necessary wrangling:

import pandas as pd
df=pd.DataFrame({'A':['a','b','c'],
        'dates':['2015-08-31 00:00:00','2015-08-24 00:00:00','2015-08-25 00:00:00']})
df.dates=df.dates.astype(str)
df['dates'] = pd.to_datetime(df.dates.str.split(',\s*').str[0])
set(df['dates'])

I end up with:

{Timestamp('2015-08-24 00:00:00'),
 Timestamp('2015-08-25 00:00:00'),
 Timestamp('2015-08-31 00:00:00')}

I need to convert the time stamps back to datetime (really, just date) format.

I've tried this based on the answer to this post:

df['dates'].to_pydatetime()

But that returns:

AttributeError: 'Series' object has no attribute 'to_pydatetime'

In my real data, the data type is: <M8[ns]

Thanks in advance!

解决方案

You can use dt.date to return a datetime.date object:

In [3]:
set(df['dates'].dt.date)

Out[3]:
{datetime.date(2015, 8, 24),
 datetime.date(2015, 8, 25),
 datetime.date(2015, 8, 31)}

这篇关于 pandas 将时间戳列转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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