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 时间戳的时间部分


基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01