在 datetime 和 Pandas Timestamp 对象之间转换 [英] Converting between datetime and Pandas Timestamp objects

查看:40
本文介绍了在 datetime 和 Pandas Timestamp 对象之间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几点:

> date1
Timestamp('2014-01-23 00:00:00', tz=None)

> date2
datetime.date(2014, 3, 26)

我在这个答案上读到我可以使用 pandas.to_datetime()Timestamps 转换为 datetime 对象,但它似乎不起作用:

and I read on this answer that I could use pandas.to_datetime() to convert from Timestamps to datetime objects, but it doesn't seem to work:

> pd.to_datetime(date1)   
Timestamp('2014-01-23 00:00:00', tz=None)

为什么?如何在这两种格式之间进行转换?

Why? How can I convert between these two formats?

推荐答案

可以使用 to_pydatetime 方法更明确:

You can use the to_pydatetime method to be more explicit:

In [11]: ts = pd.Timestamp('2014-01-23 00:00:00', tz=None)

In [12]: ts.to_pydatetime()
Out[12]: datetime.datetime(2014, 1, 23, 0, 0)

它也可以在 DatetimeIndex 上使用:

It's also available on a DatetimeIndex:

In [13]: rng = pd.date_range('1/10/2011', periods=3, freq='D')

In [14]: rng.to_pydatetime()
Out[14]:
array([datetime.datetime(2011, 1, 10, 0, 0),
       datetime.datetime(2011, 1, 11, 0, 0),
       datetime.datetime(2011, 1, 12, 0, 0)], dtype=object)

这篇关于在 datetime 和 Pandas Timestamp 对象之间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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