gpt4 book ai didi

python - 如何将日期时间移动到一天、一周或一小时的末尾

转载 作者:太空狗 更新时间:2023-10-30 01:22:58 25 4
gpt4 key购买 nike

这是一直移动到月末的代码:

import numpy as np
import pandas as pd

times = np.array([
'2013-07-22T02:10:32.000000000+0900',
'2013-07-22T01:11:13.000000000+0900',
'2013-07-21T23:23:32.000000000+0900',
'2013-07-21T05:59:21.000000000+0900',
'2013-07-21T05:57:30.000000000+0900',
'2013-07-21T05:44:27.000000000+0900',
'2013-07-20T10:45:17.000000000+0900',
'2013-07-20T10:36:53.000000000+0900',
'2013-07-20T09:57:46.000000000+0900',
'2013-07-20T09:57:06.000000000+0900',
'2013-07-20T09:30:57.000000000+0900',
'2013-07-20T08:20:27.000000000+0900',], dtype='datetime64[ns]')

dti = pd.DatetimeIndex(times)
dti.shift(1, "M").values

结果是:

array(['2013-07-31T09:00:00.000000000+0900',
'2013-07-31T09:00:00.000000000+0900',
'2013-07-31T09:00:00.000000000+0900',
'2013-07-31T09:00:00.000000000+0900',
'2013-07-31T09:00:00.000000000+0900',
'2013-07-31T09:00:00.000000000+0900',
'2013-07-31T09:00:00.000000000+0900',
'2013-07-31T09:00:00.000000000+0900',
'2013-07-31T09:00:00.000000000+0900',
'2013-07-31T09:00:00.000000000+0900',
'2013-07-31T09:00:00.000000000+0900',
'2013-07-31T09:00:00.000000000+0900'], dtype='datetime64[ns]')

但是如何将所有时间移动到小时、天或周的末尾?

最佳答案

我找到的最好的方法是 to_period & to_timestamp:

In [39]:

dti.to_period("W-SAT").to_timestamp(how="end").values

Out[39]:

array(['2013-07-27T09:00:00.000000000+0900',
'2013-07-27T09:00:00.000000000+0900',
'2013-07-27T09:00:00.000000000+0900',
'2013-07-20T09:00:00.000000000+0900',
'2013-07-20T09:00:00.000000000+0900',
'2013-07-20T09:00:00.000000000+0900',
'2013-07-20T09:00:00.000000000+0900',
'2013-07-20T09:00:00.000000000+0900',
'2013-07-20T09:00:00.000000000+0900',
'2013-07-20T09:00:00.000000000+0900',
'2013-07-20T09:00:00.000000000+0900',
'2013-07-20T09:00:00.000000000+0900'], dtype='datetime64[ns]')

In [40]:

dti.to_period("H").to_timestamp(how="end").values

Out[40]:

array(['2013-07-22T02:59:59.000000000+0900',
'2013-07-22T01:59:59.000000000+0900',
'2013-07-21T23:59:59.000000000+0900',
'2013-07-21T05:59:59.000000000+0900',
'2013-07-21T05:59:59.000000000+0900',
'2013-07-21T05:59:59.000000000+0900',
'2013-07-20T10:59:59.000000000+0900',
'2013-07-20T10:59:59.000000000+0900',
'2013-07-20T09:59:59.000000000+0900',
'2013-07-20T09:59:59.000000000+0900',
'2013-07-20T09:59:59.000000000+0900',
'2013-07-20T08:59:59.000000000+0900'], dtype='datetime64[ns]')

关于python - 如何将日期时间移动到一天、一周或一小时的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17904474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com