繁体   English   中英

从几个月的Python中获得一年零一个月

[英]Getting a year and month from a number of a months in Python

我想写一个函数:

  • 接受参数:月数(整数)
  • 返回现在到输入月份数之间的时间增量的年(int)和月(int)。

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

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

关于日期时间和日历的文档很多,以至于我有点迷茫。 感谢帮助。

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

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
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:

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

myfunc(5)应该返回(2013,12)等。

这就是我的功能产生的...
反馈人们,在随机投票之前先给它。

编辑 (更改月份添加以使准确性更完美)

现在您可以输入负数的月份并获得过去的日期,我想这就是您要寻找的

import datetime
from dateutil.relativedelta import * 

def calculate_date(number_months):
    time_now = datetime.datetime.now()  # Get now time
    time_future = time_now + relativedelta(months=+number_months)   # Add months
    return time_future.year,time_future.month  #Return year,month

我已经在计算机上测试了此脚本,并且可以完美运行

>>> calculate_data(5)
(2014, 10)

您可以python-dateutil使用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

暂无
暂无

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

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