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'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…