Python Pandas:将时间戳转换为 datetime.date
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34386751/
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
Pandas: Convert Timestamp to datetime.date
提问by kilojoules
I have a pandas column of Timestamp data
我有一个时间戳数据的熊猫列
In [27]: train["Original_Quote_Date"][6]
Out[27]: Timestamp('2013-12-25 00:00:00')
How can check equivalence of these objects to datetime.date
objects of the type
如何检查这些对象datetime.date
与类型对象的等效性
datetime.date(2013, 12, 25)
采纳答案by Andy Hayden
Use the .date
method:
使用.date
方法:
In [11]: t = pd.Timestamp('2013-12-25 00:00:00')
In [12]: t.date()
Out[12]: datetime.date(2013, 12, 25)
In [13]: t.date() == datetime.date(2013, 12, 25)
Out[13]: True
To compare against a DatetimeIndex (i.e. an array of Timestamps), you'll want to do it the other way around:
要与 DatetimeIndex(即时间戳数组)进行比较,您需要以相反的方式进行:
In [21]: pd.Timestamp(datetime.date(2013, 12, 25))
Out[21]: Timestamp('2013-12-25 00:00:00')
In [22]: ts = pd.DatetimeIndex([t])
In [23]: ts == pd.Timestamp(datetime.date(2013, 12, 25))
Out[23]: array([ True], dtype=bool)
回答by albert
You can convert a datetime.date object into a pandas Timestamp like this:
您可以将 datetime.date 对象转换为熊猫时间戳,如下所示:
#!/usr/bin/env python3
# coding: utf-8
import pandas as pd
import datetime
# create a datetime data object
d_time = datetime.date(2010, 11, 12)
# create a pandas Timestamp object
t_stamp = pd.to_datetime('2010/11/12')
# cast `datetime_timestamp` as Timestamp object and compare
d_time2t_stamp = pd.to_datetime(d_time)
# print to double check
print(d_time)
print(t_stamp)
print(d_time2t_stamp)
# since the conversion succeds this prints `True`
print(d_time2t_stamp == t_stamp)
回答by Xavier Ho
As of pandas 0.20.3, use .to_pydatetime()
to convert any pandas.DateTimeIndex
instances to Python datetime.datetime
.
从 pandas 0.20.3 开始,用于.to_pydatetime()
将任何pandas.DateTimeIndex
实例转换为 Python datetime.datetime
。