我想以上一个月和今年的格式:2016年7月.
我试过(但是没有用)并且它不打印7月但是数字:
import datetime
now = datetime.datetime.now()
print now.year, now.month(-1)
Run Code Online (Sandbox Code Playgroud)
Jon*_*nts 22
如果您正在操作日期,那么dateutil库总是非常适合Python Stdlib无法轻易覆盖的内容.
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')
Run Code Online (Sandbox Code Playgroud)
给你:
'July 2016'
Run Code Online (Sandbox Code Playgroud)
now = datetime.datetime.now()
last_month = now.month-1 if now.month > 1 else 12
last_year = now.year - 1
Run Code Online (Sandbox Code Playgroud)
获取您可以使用的月份名称
"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()[last_month-1]
Run Code Online (Sandbox Code Playgroud)
另一种使用 Pandas 的解决方案将今天转换为一个月,然后减去一(月)。使用 转换为所需格式strftime。
import datetime as dt
import pandas as pd
>>> (pd.Period(dt.datetime.now(), 'M') - 1).strftime('%B %Y')
u'July 2016'
Run Code Online (Sandbox Code Playgroud)