繁体   English   中英

从开始时间开始遍历python个月

[英]loop through python months since start time

我想遍历给定开始时间以来的几个月,并打印第一天和最后一天。 我可以手动跟踪哪个月和年,并使用calendar.monthrange(year,month)来获取天数...但这是最好的方法吗?

from datetime import date
start_date = date(2010, 8, 1)
end_date = date.today()
# I want to loop through each month and print the first and last day of the month
# 2010, 8, 1 to 2010, 8, 31
# 2010, 9, 1 to 2010, 9, 30
# ....
# 2011, 3, 1 to 2011, 3, 31
# 2011, 4, 1, to 2011, 4, 12 (ends early because it is today)

要查找一个月的最后一天,可以使用first_of_next_month-datetime.timedelta(1)。 例如:

def enumerate_month_dates(start_date, end_date):
    current = start_date
    while current <= end_date:
        if current.month >= 12:
            next = datetime.date(current.year + 1, 1, 1)
        else:
            next = datetime.date(current.year, current.month + 1, 1)
        last = min(next - datetime.timedelta(1), end_date)
        yield current, last
        current = next

dateutil模块确实支持此类操作,请参见: http ://niemeyer.net/python-dateutil#head-470fa22b2db72000d7abe698a5783a46b0731b57

好吧,在公历中,每个月的第一天都编号为1,最后一天是下个月的第一天减去一。 因此,以最简单的形式:

d = datetime.date(2010, m, 1)
print d, datetime.date(2010, m + 1, 1) - datetime.timedelta(days=1)

(这在12月不起作用,因为date()的month参数必须在1..12中)

  1. 从开始日期的第一天开始
  2. 计算该月的天数并获得下个月的开始
  3. 打印开始日期和(下个月的开始-1天)

这有效:

#!/usr/bin/python
from datetime import date, timedelta
import calendar
start_date = date(2001,8,1)
end_date = date.today()
while True:
    if start_date > end_date:
        break
    days_in_month = calendar.monthrange(start_date.year, start_date.month)[1]  # Calculate days in month for start_date
    new_ts = calendar.timegm(start_date.timetuple()) + (days_in_month * 24 * 60 * 60)  # Get timestamp for start of next month
    new_start_date = date(1,1,1).fromtimestamp(new_ts) # Convert timestamp to date object
    print start_date, new_start_date - timedelta(1)
    start_date = new_start_date

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM