Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

python - Python获取上个月和一年(Python get last month and year)

I am trying to get last month and current year in the format: July 2016.

(我正在尝试以2016年7月的格式获取上个月和本年度。)

I have tried (but that didn't work) and it does not print July but the number:

(我试过了(但是那没用),它不会打印七月,但是会打印数字:)

import datetime
now = datetime.datetime.now()
print now.year, now.month(-1)
  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're manipulating dates then the dateutil library is always a great one to have handy for things the Python stdlib doesn't cover easily.

(如果您要处理日期,那么dateutil库始终是一个很好的工具,可以方便地处理Python stdlib难以涵盖的内容。)

First, install the dateutil library if you haven't already:

(首先,如果尚未安装dateutil库,请执行dateutil :)

pip install python-dateutil

Next:

(下一个:)

from datetime import datetime
from dateutil.relativedelta import relativedelta

# Returns the same day of last month if possible otherwise end of month
# (eg: March 31st->29th Feb an July 31st->June 30th)
last_month = datetime.now() - relativedelta(months=1)

# Create string of month name and year...
text = format(last_month, '%B %Y')

Gives you:

(给你:)

'July 2016'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...