如何重置 pandas 时间戳的时间部分?
How can I reset the time part of a pandas timestamp?
我想重置 pandas.Timestamp 值中的时间部分.
我想我可以使用以下过程来做到这一点.
I want to reset time part in value of pandas.Timestamp.
I guess I can do it using the following procedure.
即使我的猜测是正确的,也需要很长时间才能完成.有没有直接的方法来实现这个目标?
Even if my guess is correct, it takes too long to do. Is there a straightforward way to achieve this goal?
在 [371] 中:ts = pd.Timestamp('2014/11/12 13:35')
In [371]: ts = pd.Timestamp('2014/11/12 13:35')
在 [372] 中:ts
In [372]: ts
输出[372]:时间戳('2014-11-12 13:35:00')
Out[372]: Timestamp('2014-11-12 13:35:00')
在 [373]: ts.hour = 0 # <-- 这就是我想要做的.
In [373]: ts.hour = 0 # <-- this is what I am trying to do.
我想你正在寻找 replace
方法(参见 docs):
I think you are looking for the replace
method (see docs):
In [18]: ts
Out[18]: Timestamp('2014-11-12 13:35:00')
In [19]: ts.replace(hour=0)
Out[19]: Timestamp('2014-11-12 00:35:00')
这是一个继承自datetime.datetime
如果要重置全时部分,则在replace
中指定所有部分:
If you want to reset the full time part, you specify all parts in replace
:
In [20]: ts.replace(hour=0, minute=0, second=0)
Out[20]: Timestamp('2014-11-12 00:00:00')
还有一个 DatetimeIndex.normalize
方法,但这在单个时间戳上不可用(我为此打开了一个问题:https://github.com/pydata/pandas/issues/8794):
There is also a DatetimeIndex.normalize
method, but this isn't available on the individual Timestamps (I opened an issue for that: https://github.com/pydata/pandas/issues/8794):
In [21]: pd.DatetimeIndex([ts]).normalize()[0]
Out[21]: Timestamp('2014-11-12 00:00:00')
这篇关于重置 pandas 时间戳的时间部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!