上个月的python日期

phi*_*ppe 111 python time date

我试图用python获取上个月的日期.这是我尝试过的:

str( time.strftime('%Y') ) + str( int(time.strftime('%m'))-1 )
Run Code Online (Sandbox Code Playgroud)

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

我用bash解决了这个麻烦

echo $(date -d"3 month ago" "+%G%m%d")
Run Code Online (Sandbox Code Playgroud)

我认为如果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)
Run Code Online (Sandbox Code Playgroud)

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

谢谢你的帮助!

bgp*_*ter 252

datetime和datetime.timedelta类是你的朋友.

  1. 今天找到.
  2. 用它来找到这个月的第一天.
  3. 使用timedelta备份一天,到上个月的最后一天.
  4. 打印您正在寻找的YYYYMM字符串.

像这样:

 >>> import datetime
 >>> today = datetime.date.today()
 >>> first = today.replace(day=1)
 >>> lastMonth = first - datetime.timedelta(days=1)
 >>> print lastMonth.strftime("%Y%m")
 201202
 >>>
Run Code Online (Sandbox Code Playgroud)

  • 你可以使用`.replace()`方法:`datetime.utcnow().replace(day = 1) - timedelta(days = 1)` (24认同)
  • @ThanePlummer:它不适用于`2013-03-31` (3认同)
  • 凉爽的!我错过了替换方法。 (2认同)
  • 您还可以链接“.replace()”函数。执行一次以获得最后一个月,然后再次执行以获得您想要的日期。首先: `d = date.today()` 然后 `one_month_ago = (d.replace(day=1) - timedelta(days=1)).replace(day=d.day)` (2认同)

Dav*_*ler 61

你应该使用dateutil.有了它,你可以使用relativedelta,它是timedelta的改进版本.

>>> import datetime 
>>> import dateutil.relativedelta
>>> now = datetime.datetime.now()
>>> print now
2012-03-15 12:33:04.281248
>>> print now + dateutil.relativedelta.relativedelta(months=-1)
2012-02-15 12:33:04.281248
Run Code Online (Sandbox Code Playgroud)

  • @mtoloo你可能错误地输入了月/月 (3认同)
  • @r_black 是的,你说得对。那是我的错。此处给出的解决方案是正确的,一年中的第一个月不需要进一步检查。 (2认同)

Iva*_*van 43

from datetime import date, timedelta

first_day_of_current_month = date.today().replace(day=1)
last_day_of_previous_month = first_day_of_current_month - timedelta(days=1)

print "Previous month:", last_day_of_previous_month.month
Run Code Online (Sandbox Code Playgroud)

要么:

from datetime import date, timedelta

prev = date.today().replace(day=1) - timedelta(days=1)
print prev.month
Run Code Online (Sandbox Code Playgroud)


Rob*_*tan 16

对于到达这里并希望获得上个月的第一天和最后一天的人:

from datetime import date, timedelta

last_day_of_prev_month = date.today().replace(day=1) - timedelta(days=1)

start_day_of_prev_month = date.today().replace(day=1) - timedelta(days=last_day_of_prev_month.day)

# For printing results
print("First day of prev month:", start_day_of_prev_month)
print("Last day of prev month:", last_day_of_prev_month)
Run Code Online (Sandbox Code Playgroud)

输出:

First day of prev month: 2019-02-01
Last day of prev month: 2019-02-28
Run Code Online (Sandbox Code Playgroud)


Gil*_*gio 12

简单,一行:

import datetime as dt
previous_month = (dt.date.today().replace(day=1) - dt.timedelta(days=1)).month
Run Code Online (Sandbox Code Playgroud)


par*_*axi 6

建立在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'))
Run Code Online (Sandbox Code Playgroud)


Ehv*_*nce 6

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

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

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

其相反的等价物是add.

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


Mah*_*fuz 5

它非常容易和简单。做这个

from dateutil.relativedelta import relativedelta
from datetime import datetime

today_date = datetime.today()
print "todays date time: %s" %today_date

one_month_ago = today_date - relativedelta(months=1)
print "one month ago date time: %s" % one_month_ago
print "one month ago date: %s" % one_month_ago.date()
Run Code Online (Sandbox Code Playgroud)

这是输出:$python2.7 main.py

todays date time: 2016-09-06 02:13:01.937121
one month ago date time: 2016-08-06 02:13:01.937121
one month ago date: 2016-08-06
Run Code Online (Sandbox Code Playgroud)