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

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

Pandas: Convert Timestamp to datetime.date

pythondatetimepandastimestamp

提问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.dateobjects of the type

如何检查这些对象datetime.date与类型对象的等效性

datetime.date(2013, 12, 25)

采纳答案by Andy Hayden

Use the .datemethod:

使用.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.DateTimeIndexinstances to Python datetime.datetime.

从 pandas 0.20.3 开始,用于.to_pydatetime()将任何pandas.DateTimeIndex实例转换为 Python datetime.datetime