python 指定时间递增_python日期的递增问题

初始化开始时间 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

还有没其他方式

用 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

delorean,这个库能很好的应对你的需求

我也补充一下,也是用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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值