Python生成器返回一系列时间 [英] Python generator to return series of times

查看:119
本文介绍了Python生成器返回一系列时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这不是Python生成器的能力范围,但是我想构建一个生成器,以便每次调用该函数时,它都会在下一分钟返回直到结束时间.

I hope this is not outside of the abilities of Python generators, but I'd like to build one so that every time the function is called, it returns the next minute up until the end time.

因此,该函数读取开始时间和结束时间,并以分钟为单位返回时间,直到覆盖了介于两者之间的所有时间为止.

So the function reads in a start and end time, and returns the time on a minute by minute basis until all the time in between has been covered.

这将如何实施? TIA

How would this be implemented? TIA

推荐答案

只是因为更少的代码行总是更好(tm):

Just because fewer lines of code is always better (tm):

def minutes(s, e):
    secs = (e - s).seconds 
    return (s + datetime.timedelta(minutes = x) for x in xrange(secs / 60 + 1))

像这样使用它:

>>> today = datetime.datetime(2012, 1, 31, 15, 20)
>>> for m in minutes(today, today + datetime.timedelta(minutes = 5)):
...     print m
2012-01-31 15:20:00
2012-01-31 15:21:00
2012-01-31 15:22:00
2012-01-31 15:23:00
2012-01-31 15:24:00
2012-01-31 15:25:00

这篇关于Python生成器返回一系列时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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