生成时间序列,步长为7秒 [英] Generate time sequence with step 7 seconds

查看:96
本文介绍了生成时间序列,步长为7秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何在Python中生成以下字符串序列?

How would you generate the following sequence of strings in Python?

00:00:00
00:00:07
00:00:14
00:00:21
...
00:00:49
00:00:56
00:01:03

该步骤为7秒.结束大约是03:30:+/-

The step is 7 seconds. The end is about 03:30:+/-

我将提供使用模块化算术的解决方案(前1200个具有小时,而不是60个具有分钟,其余为秒,并且数字应转换为字符串,单位"字符串应以"0"作为前缀).

I would come with solution that uses modular arithmetic (first 1200 to have hours, than 60 to have minutes and the remainder are seconds and the numbers should be converted to strings and "one-place" strings should be prefixed by "0").

在标准库或列表推导中使用一些辅助生成器是否有一些更聪明的(pythonic)解决方案?

Is there some smarter (pythonic) solution with using some helper generators in standard library or list comprehension?

推荐答案

def yield_times():
    from datetime import date, time, datetime, timedelta
    start = datetime.combine(date.today(), time(0, 0))
    yield start.strftime("%H:%M:%S")
    while True:
        start += timedelta(seconds=7)
        yield start.strftime("%H:%M:%S")

>>> gen = yield_times()
>>> for ii in range(5):
...     print gen.next()
... 
00:00:00
00:00:07
00:00:14
00:00:21
00:00:28

这篇关于生成时间序列,步长为7秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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