生成间隔之间的日期时间列表

生成间隔之间的日期时间列表

本文介绍了生成间隔之间的日期时间列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定两个日期时间(start_dateend_date),我想生成这两个日期之间的其他日期时间列表,新日期时间由变量分隔间隔.例如2011-10-10 和 2011-12-12 之间每 4 天一次或现在和明天晚上 19​​ 点之间每 8 小时一次.

也许大致相当于 Dateperiod PHP 类.

在 Python 中完成此任务的最有效方法是什么?

解决方案

使用 datetime.timedelta:

from datetime 导入日期、日期时间、时间增量def perdelta(开始,结束,增量):当前 = 开始而 curr 

适用于日期和日期时间对象.你的第二个例子:

>>>对于 perdelta(datetime.now(),... datetime.now().replace(hour=19) + timedelta(days=1),... timedelta(hours=8)):...打印结果...2012-05-21 17:25:47.6680222012-05-22 01:25:47.6680222012-05-22 09:25:47.6680222012-05-22 17:25:47.668022

Given two datetimes (start_date and end_date), I'd like to generate a list of other datetimes between these two dates, the new datetimes being separated by a variable interval. e.g. every 4 days between 2011-10-10 and 2011-12-12 or every 8 hours between now and tomorrow 19p.m.

Maybe something roughly equivalent to the Dateperiod PHP class.

What would be the most efficient way to accomplish this in Python?

解决方案

Use datetime.timedelta:

from datetime import date, datetime, timedelta

def perdelta(start, end, delta):
    curr = start
    while curr < end:
        yield curr
        curr += delta

>>> for result in perdelta(date(2011, 10, 10), date(2011, 12, 12), timedelta(days=4)):
...     print result
...
2011-10-10
2011-10-14
2011-10-18
2011-10-22
2011-10-26
2011-10-30
2011-11-03
2011-11-07
2011-11-11
2011-11-15
2011-11-19
2011-11-23
2011-11-27
2011-12-01
2011-12-05
2011-12-09

Works for both dates and datetime objects. Your second example:

>>> for result in perdelta(datetime.now(),
...         datetime.now().replace(hour=19) + timedelta(days=1),
...         timedelta(hours=8)):
...     print result
...
2012-05-21 17:25:47.668022
2012-05-22 01:25:47.668022
2012-05-22 09:25:47.668022
2012-05-22 17:25:47.668022

这篇关于生成间隔之间的日期时间列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 07:54