我试图用python获取前一个月的日期。 以下是我的尝试:

str( time.strftime('%Y') ) + str( int(time.strftime('%m'))-1 )

然而,这种方式有两个原因:首先,它将返回2012年2月的20122(而不是201202);其次,它将返回0而不是1月的12。

我一下子就解决了这个麻烦

echo $(date -d"3 month ago" "+%G%m%d")

我认为,如果bash有一种内置的方式来实现这一目的,那么python应该提供更好的东西,而不是强迫自己编写脚本来实现这一目标。当然我可以这样做:

if int(time.strftime('%m')) == 1:
    return '12'
else:
    if int(time.strftime('%m')) < 10:
        return '0'+str(time.strftime('%m')-1)
    else:
        return str(time.strftime('%m') -1)

我还没有测试这段代码,我不想使用它(除非我找不到任何其他方法:/)

谢谢你的帮助!


当前回答


from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

#Months(0-12) (1 for Previous month)

#last day of (n) previous month (n=months)
day = datetime(2023, 1, 13)
n = 1
lastDayMonth = ((day - relativedelta(months=n) + relativedelta(day=31)).date());

#First day of previous month (n=months=1)
firstDayMonth = ((day - relativedelta(months=n) + relativedelta(day=1)).date());

print("Last Day of Month - "+ str(lastDayMonth))
print("First Day of Month - "+ str(firstDayMonth))

#Last business day (Friday) of prev (n) month if last day on weekend
lastBusDay = (lastDayMonth - timedelta(max(1,(lastDayMonth.weekday() + 6) % 7 - 3))) if lastDayMonth.weekday() in (5,6) else lastDayMonth

print("Last Business Day of Month - " + str(lastBusinessDay))

print()

其他回答

基于bgporter的回答。

def prev_month_range(when = None): 
    """Return (previous month's start date, previous month's end date)."""
    if not when:
        # Default to today.
        when = datetime.datetime.today()
    # Find previous month: https://stackoverflow.com/a/9725093/564514
    # Find today.
    first = datetime.date(day=1, month=when.month, year=when.year)
    # Use that to find the first day of this month.
    prev_month_end = first - datetime.timedelta(days=1)
    prev_month_start = datetime.date(day=1, month= prev_month_end.month, year= prev_month_end.year)
    # Return previous month's start and end dates in YY-MM-DD format.
    return (prev_month_start.strftime('%Y-%m-%d'), prev_month_end.strftime('%Y-%m-%d'))

Datetime和Datetime。Timedelta类是您的朋友。

今天发现。 用这个找到这个月的第一天。 使用timedelta将某一天备份到上个月的最后一天。 打印您正在寻找的YYYYMM字符串。

是这样的:

 import datetime
 today = datetime.date.today()
 first = today.replace(day=1)
 last_month = first - datetime.timedelta(days=1)
 print(last_month.strftime("%Y%m"))
 

201202打印出来了。

有一个高级库dateparser,可以确定给定自然语言的过去日期,并返回相应的Python datetime对象

from dateparser import parse
parse('4 months ago')

只是为了好玩,一个使用divmod的纯数学答案。因为是乘法运算,所以它的效果很差,可以简单地检查月份的个数(如果等于12,则增加年份等)

year = today.year
month = today.month

nm = list(divmod(year * 12 + month + 1, 12))
if nm[1] == 0:
    nm[1] = 12
    nm[0] -= 1
pm = list(divmod(year * 12 + month - 1, 12))
if pm[1] == 0:
    pm[1] = 12
    pm[0] -= 1

next_month = nm
previous_month = pm

在Pendulum非常完整的库中,我们有了subtract方法(而不是“subact”):

import pendulum
today = pendulum.datetime.today()  # 2020, january
lastmonth = today.subtract(months=1)
lastmonth.strftime('%Y%m')
# '201912'

我们看到它处理跳跃的年份。

相反的等效形式是add。

https://pendulum.eustace.io/docs/#addition-and-subtraction