gpt4 book ai didi

python - 将日期范围拆分为相等的子范围,并将剩余时间分配给最后一个子范围

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:51 25 4
gpt4 key购买 nike

有没有一种更优雅/Pythonic 的方法来完成标题所说的和这个函数所做的事情?

def split_datetime_range(start, end, split):
"""Splits a range of dates into a list of equal ranges
with remaining time allocated to the last of the series.
This function doesn't overlap dates, so seconds are lost
inbetween each range

Parameters:
start - The start of the range
end - The end of the range
split - How many ranges to produce

Returns:
A list of tuples, each tuple is its own range
"""
total_seconds = int((end - start).total_seconds())
delta = total_seconds / split
starts = [start + timedelta(seconds=delta * i) for i in range(split)]
ends = [s + timedelta(seconds=delta - 1) for s in starts]
ends[len(ends) - 1] = end
return zip(starts, ends)

编辑-

一个限制是它必须采用“秒”分辨率,而不是“微秒”分辨率。这个想法是生成一个日期范围列表,提供给接受 iso8601 格式的日期(秒分辨率)的 Web 服务

最佳答案

我不确定这是否符合您的要求。

>>> from datetime import *
>>> end = datetime.now()
>>> start = end - timedelta(30)
>>> start
datetime.datetime(2013, 6, 17, 18, 35, 17, 353000)
>>> end
datetime.datetime(2013, 7, 17, 18, 35, 17, 353000)
>>> d = (end- start) / 7
>>> d
datetime.timedelta(4, 24685, 714285)
>>> [(i * d + start, (i+1)*d+start) for i in range(7)]
[(datetime.datetime(2013, 6, 17, 18, 35, 17, 353000), datetime.datetime(2013, 6,
22, 1, 26, 43, 67285)), (datetime.datetime(2013, 6, 22, 1, 26, 43, 67285), date
time.datetime(2013, 6, 26, 8, 18, 8, 781570)), (datetime.datetime(2013, 6, 26, 8
, 18, 8, 781570), datetime.datetime(2013, 6, 30, 15, 9, 34, 495855)), (datetime.
datetime(2013, 6, 30, 15, 9, 34, 495855), datetime.datetime(2013, 7, 4, 22, 1, 0
, 210140)), (datetime.datetime(2013, 7, 4, 22, 1, 0, 210140), datetime.datetime(
2013, 7, 9, 4, 52, 25, 924425)), (datetime.datetime(2013, 7, 9, 4, 52, 25, 92442
5), datetime.datetime(2013, 7, 13, 11, 43, 51, 638710)), (datetime.datetime(2013
, 7, 13, 11, 43, 51, 638710), datetime.datetime(2013, 7, 17, 18, 35, 17, 352995)
)]
>>>

如果您想要不带毫秒的 iso 格式,给定日期时间对象“now”:

>>> now
datetime.datetime(2013, 7, 17, 19, 9, 1, 835000)
>>> now.strftime('%Y-%m-%dT%H:%M:%S')
'2013-07-17T19:09:01'

关于python - 将日期范围拆分为相等的子范围,并将剩余时间分配给最后一个子范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17710519/

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