English 中文(简体)
上个月返国日期物体
原标题:Return datetime object of previous month
  • 时间:2010-08-06 14:48:49
  •  标签:
  • python
  • date

如果只有时间三角洲的建筑商有一个月的论点。 因此,这样做的最简单方式是什么?

EDIT: 我对这一点的思考太困难,如下文所述。 确实,我想要的是上个月的任何一天,因为最终我会只 gr一年和月。 因此,给出了一个日期标的,什么是返回上个月的任何日期标的的最简单方式?

最佳回答

为此:

def monthdelta(date, delta):
    m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12
    if not m: m = 12
    d = min(date.day, [31,
        29 if y%4==0 and (not y%100==0 or y%400 == 0) else 28,
        31,30,31,30,31,31,30,31,30,31][m-1])
    return date.replace(day=d,month=m, year=y)

>>> for m in range(-12, 12):
    print(monthdelta(datetime.now(), m))

    
2009-08-06 16:12:27.823000
2009-09-06 16:12:27.855000
2009-10-06 16:12:27.870000
2009-11-06 16:12:27.870000
2009-12-06 16:12:27.870000
2010-01-06 16:12:27.870000
2010-02-06 16:12:27.870000
2010-03-06 16:12:27.886000
2010-04-06 16:12:27.886000
2010-05-06 16:12:27.886000
2010-06-06 16:12:27.886000
2010-07-06 16:12:27.886000
2010-08-06 16:12:27.901000
2010-09-06 16:12:27.901000
2010-10-06 16:12:27.901000
2010-11-06 16:12:27.901000
2010-12-06 16:12:27.901000
2011-01-06 16:12:27.917000
2011-02-06 16:12:27.917000
2011-03-06 16:12:27.917000
2011-04-06 16:12:27.917000
2011-05-06 16:12:27.917000
2011-06-06 16:12:27.933000
2011-07-06 16:12:27.933000
>>> monthdelta(datetime(2010,3,30), -1)
datetime.datetime(2010, 2, 28, 0, 0)
>>> monthdelta(datetime(2008,3,30), -1)
datetime.datetime(2008, 2, 29, 0, 0)

<><>Edit>/strong> 更正也可在当天处理。

<><>Edit>/strong> 另见对“条码”的简单计算方法的解答:

d = min(date.day, calendar.monthrange(y, m)[1])
问题回答

您可使用第三方https://labix.org/python-dateutil>dateutil/code>。 模块(PyPI条目here

import datetime
import dateutil.relativedelta

d = datetime.datetime.strptime("2013-03-31", "%Y-%m-%d")
d2 = d - dateutil.relativedelta.relativedelta(months=1)
print d2

产出:

2013-02-28 00:00:00

在最初的问题被贴上“上个月的任何日期物体”之后,你可以很容易地从上个月的第一日起将1天拖走。

from datetime import datetime, timedelta

def a_day_in_previous_month(dt):
   return dt.replace(day=1) - timedelta(days=1)

病媒化的解决办法非常简单:

df[日期] - pd.DateOffset(月=1)

https://stackoverflow.com/questions/3424899/whats-the-simplest-way-to-subtract-a-个月- from-a-date-in-python/3425#3425124" s 回答(我没有足够声誉来评论),使用日历。 安排大大简化月份最后一天的计算:

import calendar
def monthdelta(date, delta):
    m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12
    if not m: m = 12
    d = min(date.day, calendar.monthrange(y, m)[1])
    return date.replace(day=d,month=m, year=y)

http://st.com/pressreleases/ ∗∗∗∗∗

我认为,简单的办法是使用潘达斯这样的日期:

import pandas as pd
date_1 = pd.to_datetime("2013-03-31", format="%Y-%m-%d") - pd.DateOffset(months=1)

其结果将是时标。

If only timedelta had a month argument in it s constructor. So what s the simplest way to do this?

你们想要的是,从3月30日这个月中减去一个月? 这就是增加或减少几个月的问题:几个月的时间不同! 在有些申请中,一种例外是适当的,在另一些情况下,“上个月的最后一天”是科索沃使用的(但如果存在的话,真的希望是Feb 30的话),这样,在另一个月里,如果再补充一个月的时间是而不是整体上不操作!”),在另一些情况下,你想要在表明事实的日期之外保持一定时间,例如,“如果说是Feb 28,那么我真的希望的话,那么的话,那么,那么就再增加或推回另一个月,从而可以再次确定事情(后者显然需要一个具有数据加附的类别)。

不可能真正解决所有申请都无法容忍的问题,而且你没有告诉我们,你对这一拖延行动的具体需要是什么,因此,我们无法在此提供更多的帮助。

如果你们想要的是上个月的任何一天,你所能做的最简单事情就是从现在起的几天时间减去,那天将给你上个月的最后一天。

例如,从任何日期开始:

>>> import datetime                                                                                                                                                                 
>>> today = datetime.date.today()                                                                                                                                                   
>>> today
datetime.date(2016, 5, 24)

减去我们获得的日期:

>>> last_day_previous_month = today - datetime.timedelta(days=today.day)
>>> last_day_previous_month
datetime.date(2016, 4, 30)

这足以满足上个月你每天的简单需要。

但是,现在,你也可以在月份获得任何一天的时间,包括你开始的同一天(即,相当于一个月的时间):

>>> same_day_last_month = last_day_previous_month.replace(day=today.day)
>>> same_day_last_month
datetime.date(2016, 4, 24)

当然,你需要在30天或从2月份失踪的几天内仔细看第31天(照顾年限),但这也很容易做到:

>>> a_date = datetime.date(2016, 3, 31)                                                                                                                                             
>>> last_day_previous_month = a_date - datetime.timedelta(days=a_date.day)
>>> a_date_minus_month = (
...     last_day_previous_month.replace(day=a_date.day)
...     if a_date.day < last_day_previous_month.day
...     else last_day_previous_month
... )
>>> a_date_minus_month
datetime.date(2016, 2, 29)

在大多数情况下,什么是

from datetime import date

current_date =date.today()
current_month = current_date.month
last_month = current_month - 1 if current_month != 1 else 12  
today_a_month_ago = date(current_date.year, last_month, current_date.day)

这对我来说似乎最简单。

<>注: 我将第二行改为最后一行,这样,如果本月是1月,它将按@Nick的评论开展工作。

在大多数情况下,如果目前的日期是某一月的第31日,结果将无效,因为前一个月将有31天(7月和8月除外),正如“一个板块”所指出的。

上个月的最后一天返回:

>>> import datetime
>>> datetime.datetime.now() - datetime.timedelta(days=datetime.datetime.now().day)
datetime.datetime(2020, 9, 30, 14, 13, 15, 67582)

上个月返回:

>>> x = datetime.datetime.now() - datetime.timedelta(days=datetime.datetime.now().day)
>>> x.replace(day=datetime.datetime.now().day)
datetime.datetime(2020, 9, 7, 14, 22, 14, 362421)

在政府财政年度,Q4从10月1日开始。 说明 我将日期改为季度,并公布日期。

import pandas as pd

df[ Date ] =  1/1/2020 
df[ Date ] = pd.to_datetime(df[ Date ])              #returns 2020-01-01
df[ NewDate ] = df.Date - pd.DateOffset(months=3)    #returns 2019-10-01 <---- answer

# For fun, change it to FY Quarter  2019Q4 
df[ NewDate ] = df[ NewDate ].dt.year.astype(str) +  Q  + df[ NewDate ].dt.quarter.astype(str)

# Convert  2019Q4  back to 2019-10-01
df[ NewDate ] = pd.to_datetime(df.NewDate)

一个线人?

previous_个月_date = (当值-日期-timedelta (days= Current_date.day+1))。replace(day=当值_date.day)

刚才尝试的简单办法

from datetime import datetime
from django.utils import timezone





current = timezone.now()
if current.month == 1:
     month = 12
else:
     month = current.month - 1
current = datetime(current.year, month, current.day)

下面是code,仅作此规定。 . ......

def add_one_month(t):
    """Return a `datetime.date` or `datetime.datetime` (as given) that is
    one month earlier.

    Note that the resultant day of the month might change if the following
    month has fewer days:

        >>> add_one_month(datetime.date(2010, 1, 31))
        datetime.date(2010, 2, 28)
    """
    import datetime
    one_day = datetime.timedelta(days=1)
    one_month_later = t + one_day
    while one_month_later.month == t.month:  # advance to start of next month
        one_month_later += one_day
    target_month = one_month_later.month
    while one_month_later.day < t.day:  # advance to appropriate day
        one_month_later += one_day
        if one_month_later.month != target_month:  # gone too far
            one_month_later -= one_day
            break
    return one_month_later

def subtract_one_month(t):
    """Return a `datetime.date` or `datetime.datetime` (as given) that is
    one month later.

    Note that the resultant day of the month might change if the following
    month has fewer days:

        >>> subtract_one_month(datetime.date(2010, 3, 31))
        datetime.date(2010, 2, 28)
    """
    import datetime
    one_day = datetime.timedelta(days=1)
    one_month_earlier = t - one_day
    while one_month_earlier.month == t.month or one_month_earlier.day > t.day:
        one_month_earlier -= one_day
    return one_month_earlier

考虑到一个(年、月)图,每月从11-12个月开始,试图:

>>> from datetime import datetime
>>> today = datetime.today()
>>> today
datetime.datetime(2010, 8, 6, 10, 15, 21, 310000)
>>> thismonth = today.year, today.month
>>> thismonth
(2010, 8)
>>> lastmonth = lambda (yr,mo): [(y,m+1) for y,m in (divmod((yr*12+mo-2), 12),)][0]
>>> lastmonth(thismonth)
(2010, 7)
>>> lastmonth( (2010,1) )
(2009, 12)

假设每年有12个月。

def month_sub(year, month, sub_month):
    result_month = 0
    result_year = 0
    if month > (sub_month % 12):
        result_month = month - (sub_month % 12)
        result_year = year - (sub_month / 12)
    else:
        result_month = 12 - (sub_month % 12) + month
        result_year = year - (sub_month / 12 + 1)
    return (result_year, result_month)

>>> month_sub(2015, 7, 1)    
(2015, 6)
>>> month_sub(2015, 7, -1)
(2015, 8)
>>> month_sub(2015, 7, 13)
(2014, 6)
>>> month_sub(2015, 7, -14)
(2016, 9)

页: 1 采用以下代码,从特定日期起回封:

your_date =  datetime.strptime(input_date, "%Y-%m-%d")  #to convert date(2016-01-01) to timestamp
start_date=your_date    #start from current date

#Calculate Month
for i in range(0,n):    #n = number of months you need to go back
    start_date=start_date.replace(day=1)    #1st day of current month
    start_date=start_date-timedelta(days=1) #last day of previous month

#Calculate Day
if(start_date.day>your_date.day):   
    start_date=start_date.replace(day=your_date.day)            

print start_date

For eg: input date = 28/12/2015 Calculate 6 months previous date.

I) CALCULATE MONTH: This step will give you the start_date as 30/06/2015.
Note that after the calculate month step you will get the last day of the required month.

II)CALCULATE DAY: Condition if(start_date.day>your_date.day) checks whether the day from input_date is present in the required month. This handles condition where input date is 31(or 30) and the required month has less than 31(or 30 in case of feb) days. It handles leap year case as well(For Feb). After this step you will get result as 28/06/2015

如果这一条件得不到满足,起算日期仍然是上个月的最后日期。 因此,如果你把2008年12月31日定为投入日期,并要求在前一日期提前6个月,将给你30/06/2015。

您可在X个月之前/之后利用以下职能。

from datetime import date

def next_month(given_date, month):
    yyyy = int(((given_date.year * 12 + given_date.month) + month)/12)
    mm = int(((given_date.year * 12 + given_date.month) + month)%12)

    if mm == 0:
        yyyy -= 1
        mm = 12

    return given_date.replace(year=yyyy, month=mm)


if __name__ == "__main__":
    today = date.today()
    print(today)

    for mm in [-12, -1, 0, 1, 2, 12, 20 ]:
        next_date = next_month(today, mm)
        print(next_date)

我认为,这一答案是可以理解的:

def month_delta(dt, delta):
    year_delta, month = divmod(dt.month + delta, 12)

    if month == 0:
        # convert a 0 to december
        month = 12
        if delta < 0:
            # if moving backwards, then it s december of last year
            year_delta -= 1

    year = dt.year + year_delta

    return dt.replace(month=month, year=year)

for delta in range(-20, 21):
    print(delta, "->", month_delta(datetime(2011, 1, 1), delta))

-20 -> 2009-05-01 00:00:00
-19 -> 2009-06-01 00:00:00
-18 -> 2009-07-01 00:00:00
-17 -> 2009-08-01 00:00:00
-16 -> 2009-09-01 00:00:00
-15 -> 2009-10-01 00:00:00
-14 -> 2009-11-01 00:00:00
-13 -> 2009-12-01 00:00:00
-12 -> 2010-01-01 00:00:00
-11 -> 2010-02-01 00:00:00
-10 -> 2010-03-01 00:00:00
-9 -> 2010-04-01 00:00:00
-8 -> 2010-05-01 00:00:00
-7 -> 2010-06-01 00:00:00
-6 -> 2010-07-01 00:00:00
-5 -> 2010-08-01 00:00:00
-4 -> 2010-09-01 00:00:00
-3 -> 2010-10-01 00:00:00
-2 -> 2010-11-01 00:00:00
-1 -> 2010-12-01 00:00:00
0 -> 2011-01-01 00:00:00
1 -> 2011-02-01 00:00:00
2 -> 2011-03-01 00:00:00
3 -> 2011-04-01 00:00:00
4 -> 2011-05-01 00:00:00
5 -> 2011-06-01 00:00:00
6 -> 2011-07-01 00:00:00
7 -> 2011-08-01 00:00:00
8 -> 2011-09-01 00:00:00
9 -> 2011-10-01 00:00:00
10 -> 2011-11-01 00:00:00
11 -> 2012-12-01 00:00:00
12 -> 2012-01-01 00:00:00
13 -> 2012-02-01 00:00:00
14 -> 2012-03-01 00:00:00
15 -> 2012-04-01 00:00:00
16 -> 2012-05-01 00:00:00
17 -> 2012-06-01 00:00:00
18 -> 2012-07-01 00:00:00
19 -> 2012-08-01 00:00:00
20 -> 2012-09-01 00:00:00

一段时间前,我走过以下算法,在<条码><>>>日码/代码>或<条码>日上花了很多时间加固和减缩。

www.un.org/Depts/DGACM/index_spanish.htm 如果新月无法提供<代码>/code>,这将失败。 在<代码>日 = 1上,我一直使用这一编号。

3.x:

def increment_month(d, add=1):
    return date(d.year+(d.month+add-1)//12, (d.month+add-1) % 12+1, 1)

若要将<代码>//12改为仅限/12>,因为暗示了分类。

我最近在一个缺省档案中使用了这种说法,当时一个文字开始获得这些有用的全球:

MONTH_THIS = datetime.date.today()
MONTH_THIS = datetime.date(MONTH_THIS.year, MONTH_THIS.month, 1)

MONTH_1AGO = datetime.date(MONTH_THIS.year+(MONTH_THIS.month-2)//12,
                           (MONTH_THIS.month-2) % 12+1, 1)

MONTH_2AGO = datetime.date(MONTH_THIS.year+(MONTH_THIS.month-3)//12,
                           (MONTH_THIS.month-3) % 12+1, 1)

我使用了以下方法,将“n_个月”改为“日标:

from datetime import datetime, timedelta

def substract_months(original_date: datetime, n_months:int) -> datetime:
    ref_date = original_date
    for i in range(0, number_of_months):
        ref_date = (ref_date.replace(day=1) - timedelta(days=1)).replace(day=1)
    ref_date = ref_date.replace(day=original_date.day)
    return ref_date

您可将其用作:

print(substract_months(original_date=datetime(2022, 11, 16), number_of_months=2))

返回:

2022-09-16 00:00:00




相关问题
Mysql compaire two dates from datetime?

I was try to measure what is faster and what should be the best way to compare two dates, from datetime record in MySql db. There are several approaches how to grab a date from date time, but I was ...

iPhone Date Picker rolls over to 2010 on December 27th?

So I implemented a UIDatepicker in one of my applications for scheduling and autodialing teleconferences... everything is pretty much ready to go except, while testing I noticed that when the date ...

Convert date Python

I have MMDDYY dates, i.e. today is 111609 How do I convert this to 11/16/2009, in Python?

specifying date format when using $form->inputs() in CakePHP

I am wondering if there is a way to specify the date format in the forms created using CakePHP s $form->inputs(); Please note that this is not the individual $form->input() but instead $form->inputs() ...

NSDateFormat, super simple! Where am I screwing up?

Ok, this is really simple, maybe I m a getting a bit burnt out, but seems like it should work, Query XML feed, put out date string, format, display in a cell. The issue is I m a getting a NULL ...

sqlite writing a date into an email

I am exporting a date value from sqlite and placing it into an email. The date appears like this 279498721.322872 I am using Objective C in an Iphone App. Does anyone know how to make this export ...