获取(年,月)最近的X个月 [英] Get (year,month) for the last X months

查看:142
本文介绍了获取(年,月)最近的X个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个很简单的事情:
我需要一个元组列表($,$,$)包括)从今天开始。所以,对于x = 10和今天(2011年7月),命令应该输出:

I got a very simple thing to to in python: I need a list of tuples (year,month) for the last x months starting (and including) from today. So, for x=10 and today(July 2011), the command should output:

[(2011, 7), (2011, 6), (2011, 5), (2011, 4), (2011, 3), 
(2011, 2), (2011, 1), (2010, 12), (2010, 11), (2010, 10)]

只应使用默认的datetime实现的python。我想出了以下解决方案:

Only the default datetime implementation of python should be used. I came up with the following solution:

import datetime
[(d.year, d.month) for d in [datetime.date.today()-datetime.timedelta(weeks=4*i) for i in range(0,10)]]

此解决方案为我的测试用例输出正确的解决方案,但我不满意此解决方案:假设一个月有四个星期,这根本不是真的。我可以用 days = 30 替换 weeks = 4 ,这将使一个更好的解决方案,但仍然不正确。

This solution outputs the correct solution for my test cases but I'm not comfortable with this solution: It assumes that a month has four weeks and this is simply not true. I could replace the weeks=4 with days=30 which would make a better solution but it is still not correct.

我想到的另一个解决方案是使用简单的数学,并从月计数器中减去1,如果月计数器为0,则从年计数器中减去1 。这个解决方案的问题:它需要更多的代码,也不是非常可读的。

The other solution which came to my mind is to use simple maths and subtract 1 from a months counter and if the month-counter is 0, subtract 1 from a year counter. The problem with this solution: It requires more code and isn't very readable either.

那么这怎么可以正确地完成?

So how can this be done correctly?

推荐答案

我没有看到它记录在任何地方,但 time.mktime 将滚动到正确的当超出范围时,包括负值,月份值:

I don't see it documented anywhere, but time.mktime will "roll over" into the correct year when given out-of-range, including negative, month values:

x = 10
now = time.localtime()
print [time.localtime(time.mktime((now.tm_year, now.tm_mon - n, 1, 0, 0, 0, 0, 0, 0)))[:2] for n in range(x)]

这篇关于获取(年,月)最近的X个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆