Reset time part of a pandas timestamp(重置 pandas 时间戳的时间部分)
问题描述
如何重置 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 时间戳的时间部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:重置 pandas 时间戳的时间部分


- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01