如何在python中返回带有中间时间的时间列表?

时间:2018-09-17 22:26:51

标签: python-3.x

如何返回所有中间秒数的列表?例如,对于“ 10:10:10”和“ 15:15:15”,返回:["10:10:10", "10:10:11", ... "15:15:14", "15:15:15"]

我必须使用datatime模块并做一名会计师吗?

在python文档中找不到所需的结果。您能推荐什么?

2 个答案:

答案 0 :(得分:0)

您可以使用pandas功能和date_range功能

如果要将它们用作日期时间对象:

import pandas as pd

pd.date_range("10:10:10","15:15:15", freq='S').time

哪个给你:

array([datetime.time(10, 10, 10), datetime.time(10, 10, 11),
   datetime.time(10, 10, 12), ..., datetime.time(15, 15, 13),
   datetime.time(15, 15, 14), datetime.time(15, 15, 15)], dtype=object)

或作为格式字符串:

pd.date_range("10:10:10","15:15:15", freq='S').strftime('%H:%M:%S')

给你

array(['10:10:10', '10:10:11', '10:10:12', ..., '15:15:13', '15:15:14',
   '15:15:15'], dtype='<U8')

答案 1 :(得分:0)

您可以编写类似于range的生成器:

import datetime as dt

def time_range(t0,tn,t_inc=1):
   def add_secs_to_time(timeval, secs_to_add):
      dummy_date = dt.date(1, 1, 1)
      full_datetime = dt.datetime.combine(dummy_date, timeval)
      added_datetime = full_datetime + dt.timedelta(seconds=secs_to_add)
      return added_datetime.time()

   t=t0
   yield t
   while t<tn:
      t=add_secs_to_time(t,t_inc)
      yield t

然后像这样使用:

t0=dt.time(*map(int,'10:10:10'.split(':')))
tn=dt.time(*map(int,'15:15:15'.split(':')))
times=time_range(t0,tn) 

>>> list(times)
[datetime.time(10, 10, 10), datetime.time(10, 10, 11), datetime.time(10, 10, 12)...datetime.time(15, 15, 11), datetime.time(15, 15, 12), datetime.time(15, 15, 13), datetime.time(15, 15, 14), datetime.time(15, 15, 15)]

或者,您的输出:

>>> list(map(str, times))
['10:10:10', '10:10:11', '10:10:12', '10:10:13' ...
'15:15:13', '15:15:14', '15:15:15']