将 `pandas.tslib.Timestamp` 对象转换为 `datetime`
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32108564/
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
Converting a `pandas.tslib.Timestamp` object to `datetime`
提问by Jojo
I am trying to convert a pandas.tslib.Timestampobject to datetime.df['orig_iss_dt']is the pandas.tslib.Timestampobject. I used the answer hereto try and do this, but find that print(type(origination))still returns the same type.
我正在尝试将pandas.tslib.Timestamp对象转换为datetime. df['orig_iss_dt']是pandas.tslib.Timestamp对象。我使用这里的答案来尝试执行此操作,但发现print(type(origination))仍然返回相同的类型。
df['orig_iss_dt'] = df['orig_iss_dt'].apply(lambda x: datetime.date(x.year,x.month,x.day))
for (i, row) in df:
origination = row.orig_iss_dt
print(type(origination))
回答by joris
The easiest way to convert a pandas Timestampto datetime.datetimeis to use the to_pydatetimemethod. This can be called on Timestampdirectly or on the series:
到大Pandas转换的最简单的方法Timestamp来datetime.datetime是使用to_pydatetime方法。这可以直接调用Timestamp或在系列上调用:
In [15]: s = pd.Series(pd.date_range('2012-01-01', periods=3))
In [16]: s
Out[16]:
0 2012-01-01
1 2012-01-02
2 2012-01-03
dtype: datetime64[ns]
In [17]: s[0]
Out[17]: Timestamp('2012-01-01 00:00:00')
In [18]: s.dt.to_pydatetime()
Out[18]:
array([datetime.datetime(2012, 1, 1, 0, 0),
datetime.datetime(2012, 1, 2, 0, 0),
datetime.datetime(2012, 1, 3, 0, 0)], dtype=object)
But note that this is often times not needed, as Timestampis a subclass of datetime.datetime.
但请注意,这往往是不需要的时候,因为Timestamp是的一个子类datetime.datetime。

