Python 在 datetime 和 Pandas Timestamp 对象之间转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22825349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:45:58  来源:igfitidea点击:

Converting between datetime and Pandas Timestamp objects

pythondatetimepandas

提问by Amelio Vazquez-Reina

I have the following:

我有以下几点:

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

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

and I read on this answerthat I could use pandas.to_datetime()to convert from Timestampsto datetimeobjects, but it doesn't seem to work:

我阅读了这个答案,我可以用它pandas.to_datetime()来转换Timestampsdatetime对象,但它似乎不起作用:

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

Why? How can I convert between these two formats?

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

采纳答案by Andy Hayden

You can use the to_pydatetime method to be more explicit:

您可以使用 to_pydatetime 方法更明确:

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)

It's also available on a DatetimeIndex:

它也可以在 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)

回答by behzad.nouri

>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')

回答by Konstantin Smirnov

Pandas Timestamp to datetime.datetime:

熊猫时间戳到 datetime.datetime:

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

datetime.datetime to Timestamp

datetime.datetime 到时间戳

pd.Timestamp(datetime(2014, 1, 23))