从Python中的月份数中得到一年和一个月

2024-04-18 06:55:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个函数:

  • 接受参数:月数(int)
  • 返回从现在到输入月数之间的timedelta的年(int)和月(int)。你知道吗

示例:我们在2014年5月,因此:

  • myfunc(0)应该返回(2014,5)
  • myfunc(12)应该返回(2013,5)
  • myfunc(5)应该返回(2013,12)
  • 等等

有很多关于日期时间和日历的文档,以至于我有点迷路了。谢谢你的帮助。你知道吗

注意:我需要一个准确的方法,而不是一个近似值:)


Tags: 方法函数文档示例参数时间myfunctimedelta
3条回答
from time import strftime, localtime, time
from calendar import monthrange
def uberdate(n):
    if n == 0: return strftime('%Y, %m').split(', ')
    month = int(strftime('%m'))
    aDay = 60*60*24
    offset = aDay # One day to start off with
    for i in range(0, n):
        while int(strftime('%m', localtime(time()-offset))) == month:
            offset = offset+aDay
        month = int(strftime('%m', localtime(time()-offset)))
    return strftime('%Y, %m', localtime(time()-offset)).split(', ')

print(uberdate(5))

这将产生:

[torxed@archie ~]$ python test.py 
[2013, 12]

我不知道为什么我会投反对票,但引用OP的话:

Example : we are in may 2014, so:

myfunc(5) should return (2013, 12) etc.

这就是我的函数所产生的…
反馈给其他人,在随机投票前给予反馈。你知道吗

您可以使用python-dateutil模块来实现这一点。https://pypi.python.org/pypi/python-dateutil

def return_year_date(delta_month):
    from datetime import date
    from dateutil.relativedelta import relativedelta

    new_date = date.today() + relativedelta(months= -delta_month)

    return new_date.year, new_date.month
import datetime

def myfunc(num_of_months):
    today = datetime.date.today()
    num_of_months = today.year * 12 + today.month - 1 - num_of_months
    year = num_of_months / 12
    month = num_of_months % 12 + 1
    return year, month

相关问题 更多 >