如何在几天,几小时,几周和几个月之后迭代一个时间跨度? [英] How to iterate over a timespan after days, hours, weeks and months?

查看:84
本文介绍了如何在几天,几小时,几周和几个月之后迭代一个时间跨度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在几天,几小时,几周或几个月后迭代一个时间跨度?



类似的东西:

 用于foo中的日期(from_date,to_date,delta = HOURS):
打印日期

其中foo是一个函数,返回迭代器。我一直在研究日历模块,但是它只适用于一个特定的年份或月份,不适用于日期之间。

解决方案

使用 dateutil 及其rrule实现,如下所示:

  from dateutil导入规则
from datetime导入datetime,timedelta

now = datetime.now()
percentDaysLater = now + timedelta( days = 100)dt in rrule.rrule(rrule.MONTHLY,dtstart = now,until = hundredDaysLater)


print dt
/ pre>

输出为

  2008-09-30 23: 29:54 
2008-10-30 23:29:54
2008-11-30 23:29:54
2008-12-30 23:29:54

用每年,每月,每周,每天,每小时,半年或第二替换每月。



此食谱具有在所有情况下(包括MONTHLY)均可工作的优势。我唯一需要注意的是,如果您传递的日期数字并非所有月份都存在,那么它将跳过那些月份。


How do I iterate over a timespan after days, hours, weeks or months?

Something like:

for date in foo(from_date, to_date, delta=HOURS):
    print date

Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.

解决方案

Use dateutil and its rrule implementation, like so:

from dateutil import rrule
from datetime import datetime, timedelta

now = datetime.now()
hundredDaysLater = now + timedelta(days=100)

for dt in rrule.rrule(rrule.MONTHLY, dtstart=now, until=hundredDaysLater):
    print dt

Output is

2008-09-30 23:29:54
2008-10-30 23:29:54
2008-11-30 23:29:54
2008-12-30 23:29:54

Replace MONTHLY with any of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY. Replace dtstart and until with whatever datetime object you want.

This recipe has the advantage for working in all cases, including MONTHLY. Only caveat I could find is that if you pass a day number that doesn't exist for all months, it skips those months.

这篇关于如何在几天,几小时,几周和几个月之后迭代一个时间跨度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆