我想要两个日期之间的日期范围。结果值将类似于它应该支持字符串操作,或者它应该是字符串。
我尝试过以下代码,但我根本没有对日期对象做任何事情。
import datetime
def generate_dates(start_date, end_date):
td = datetime.timedelta(hours=24)
current_date = start_date
while current_date <= end_date:
print current_date
current_date += td
start_date = datetime.date(2010, 1, 2)
end_date = datetime.date(2010, 1, 5)
generate_dates(start_date, end_date)
当我试图打印当前日期current_date [0:4]时,它会抛出这样的错误。
Traceback (most recent call last):
File "C:/Users/Gopi/Desktop/d.py", line 12, in <module>
generate_dates(start_date, end_date)
File "C:/Users/Gopi/Desktop/d.py", line 7, in generate_dates
print current_date[0]
TypeError: 'datetime.date' object is not subscriptable
拜托,帮帮我
答案 0 :(得分:1)
使用yield
关键字:
import datetime
def generate_dates(start_date, end_date):
td = datetime.timedelta(hours=24)
current_date = start_date
while current_date <= end_date:
yield current_date
current_date += td
start_date = datetime.date(2010, 1, 2)
end_date = datetime.date(2010, 1, 5)
for date in generate_dates(start_date, end_date):
print date