初始化开始时间 2016-07-01
设置日期为31
递增
2016-07-01
2016-07-02
...
2016-07-31
除了
count = 0
while (count < 31):
count =count+1
print '2016-07-',count
还有没其他方式
delorean,这个库能很好的应对你的需求
用 datetime
datetime 方便又強大, 值得投資一下
from datetime import date, timedelta
def gen_dates(bdate, days):
day = timedelta(days=1)
for i in range(days):
yield bdate + day*i
if __name__ == '__main__':
bdate = date(2016, 7, 1)
for d in gen_dates(bdate, 31):
print(d)
結果:
2016-07-01
2016-07-02
...
2016-07-30
2016-07-31
代碼說明:
date(year, month, day)
可以很輕鬆地製造出日期
timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)
可以製造出時間間隔
然後你可以用一般的代數來操作日期計算:
>>> d = date(2016, 7, 1) # 產生 2016-07-01 這個日期
>>> day = timedelta(days=1) # 產生 1 天的時間間隔
>>> print(d+day) # 印出 2016-07-01 + 1 天
2016-07-02
我回答過的問題: Python-QA
我猜你是这个意思?不知道对不对
yearMonth = "2016-07"
days = 31
for day in range(1, days+1):
if len(str(day)) < 2:
day = "0%s" % day
print "%s-%s" % (yearMonth, day)
如果是单纯打印一个月的时间,使用calendar未尝不可
In [37]: import calendar
In [38]: print calendar.month(2016,7)
July 2016
Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
感谢你的邀请.
我觉得 dokelung 的答案已经很好了.
datetime 的用法,请参考以下博客,写的比较详细.
http://www.cnblogs.com/rollenholt/archive/2012/04/11/2441699.html
我也补充一下,也是用datetime模块
这个是我之前自己写的获取日期下一天的函数,日期格式用的是tup = (year,month,day),
你只要加一句 s = '-'.join(tup),就是你要的形式了
import datetime
def next_day(x):
# x is a date tuple, its element can be int or str
# make sure your tuple is available
date = datetime.date( int(x[0]), int(x[1]), int(x[2]))
date += datetime.timedelta(days = 1)
yy = str(date.year)
mm = str(date.month)
dd = str(date.day)
# return a tuple of string to build url
return (yy, mm.zfill(2), dd.zfill(2))