关于for 循环的疑问
程序代码:
import datetime def date_range(start_date, peroids, days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0): ############只有两行井号之间的代码才是我写的,其它都是平台的答题模板##################### p = 5-peroids peroids -= 1 k =start_date+ datetime.timedelta(days=days*p, seconds=seconds*p, microseconds=microseconds*p, milliseconds=milliseconds*p, minutes=minutes*p, hours=hours*p, weeks=weeks*p ) return k #################################### start = datetime.datetime.strptime('2019-03-22 12:00:00', '%Y-%m-%d %H:%M:%S') for d in date_range(start, 5, days=1): #报错信息出现在这一行,datetime.datetime对象 不可被复用/迭代 print(d) print('-------------------') for d in date_range(start, 5, minutes=2): print(d) print('-------------------') for d in date_range(start, 5, weeks=3, hours=1): print(d)
Exited with error status 1
Traceback (most recent call last):
File "99f387d91c50749fb27fccb205915d2c", line 22, in <module>
for d in date_range(start, 5, days=1):
TypeError: 'datetime.datetime' object is not iterable
Traceback (most recent call last):
File "99f387d91c50749fb27fccb205915d2c", line 22, in <module>
for d in date_range(start, 5, days=1):
TypeError: 'datetime.datetime' object is not iterable
该程序所期望的Output如下:
2019-03-22 12:00:00
2019-03-23 12:00:00
2019-03-24 12:00:00
2019-03-25 12:00:00
2019-03-26 12:00:00
-------------------
2019-03-22 12:00:00
2019-03-22 12:02:00
2019-03-22 12:04:00
2019-03-22 12:06:00
2019-03-22 12:08:00
-------------------
2019-03-22 12:00:00
2019-04-12 13:00:00
2019-05-03 14:00:00
2019-05-24 15:00:00
2019-06-14 16:00:00
2019-03-23 12:00:00
2019-03-24 12:00:00
2019-03-25 12:00:00
2019-03-26 12:00:00
-------------------
2019-03-22 12:00:00
2019-03-22 12:02:00
2019-03-22 12:04:00
2019-03-22 12:06:00
2019-03-22 12:08:00
-------------------
2019-03-22 12:00:00
2019-04-12 13:00:00
2019-05-03 14:00:00
2019-05-24 15:00:00
2019-06-14 16:00:00
我的问题在于,我不了解下面这段代码,运行起来有什么效果
程序代码:
for d in date_range(start, 5, days=1): print(d) ########################################是不是相当于下面的循环? for i=0 to 5: d=date_range(start,5,days=1) print(d) ########################################还是相当于下面的循环?如果是,for循环怎么知道是哪个常量作为迭代变量的? for i=0 to 5: d=date_range(start,i,days=1) print(d)