問題描述
如何重置 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.
- 步驟 1) 時間戳到日期時間類型
- 第 2 步)日期時間到秒
- 第 3 步)以秒為單位截斷時間部分
- 第 4 步)將秒數恢復到時間戳
即使我的猜測是正確的,也需要很長時間才能完成.有沒有直接的方法來實現這個目標?
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 時間戳的時間部分的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!