我正在尝试以2016年7月的格式获取上个月和今年。
我试过了(但没有成功(,它没有打印七月,而是数字:
import datetime
now = datetime.datetime.now()
print now.year, now.month(-1)
如果您正在操作日期,那么dateutil库总是一个很好的库,可以方便地处理Python stdlib不容易涵盖的内容。
首先,如果您还没有安装dateutil
库:
pip install python-dateutil
下一篇:
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')
给你:
'July 2016'
now = datetime.datetime.now()
last_month = now.month-1 if now.month > 1 else 12
last_year = now.year - 1
要获得月份名称,可以使用
"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()[last_month-1]
使用Pandas的替代解决方案,它将今天转换为一个月周期,然后减去一(月(。使用strftime
转换为所需格式。
import datetime as dt
import pandas as pd
>>> (pd.Period(dt.datetime.now(), 'M') - 1).strftime('%B %Y')
u'July 2016'
from datetime import date, timedelta
last_month = date.today().replace(day=1) - timedelta(1)
last_month.strftime("%B %Y")
date.today().replace(day=1)
获得当月的第一天,减去1天将获得上月的最后一天
您可以只使用Python日期时间库来实现这一点。
说明:
- 将今天的日期中的日期替换为1,这样您就可以得到本月的第一天
- Doing-timedelta(days=1(将给出上个月的最后一天
- 格式化,并使用"%B%Y"转换为所需的格式
import datetime as dt
format(dt.date.today().replace(day=1) - dt.timedelta(days=1), '%B %Y')
>>>'June-2019'
def subOneMonth(dt):
day = dt.day
res = dt.replace(day=1) - datetime.timedelta(days =1)
try:
res.replace(day= day)
except ValueError:
pass
return res
print subOneMonth(datetime.datetime(2016,07,11)).strftime('%d, %b %Y')
11, Jun 2016
print subOneMonth(datetime.datetime(2016,01,11)).strftime('%d, %b %Y')
11, Dec 2015
print subOneMonth(datetime.datetime(2016,3,31)).strftime('%d, %b %Y')
29, Feb 2016
from datetime import datetime, timedelta, date, time
#Datetime: 1 month ago
datetime_to = datetime.now().replace(day=15) - timedelta(days=30 * 1)
#Date : 2 months ago
date_to = date.today().replace(day=15) - timedelta(days=30 * 2)
#Date : 12 months ago
date_to = date.today().replace(day=15) - timedelta(days=30 *12)
#Accounting standards: 13 months ago of pervious day
date_ma = (date.today()-timedelta(1)).replace(day=15)-timedelta(days=30*13)
yyyymm = date_ma.strftime('%Y%m') #201909
yyyy = date_ma.strftime('%Y') #2019
#Error Range Test
from datetime import datetime, timedelta, date, time
import pandas as pd
for i in range(1,120):
pdmon = (pd.Period(dt.datetime.now(), 'M')-i).strftime('%Y%m')
wamon = (date.today().replace(day=15)-timedelta(days=30*i)).strftime('%Y%m')
if pdmon != wamon:
print('Incorrect %s months ago:%s,%s' % (i,pdmon,wamon))
break
#Incorrect 37 months ago:201709,201710
import datetime as dt
- .remove(day=1(将今天的日期替换为该月的第一天,很简单
- 减去timedelta(1(减去1天,得出上个月的最后一天
last_month = dt.datetime.today().replace(day=1) - dt.timedelta(1)
- 用户想要单词July,而不是第6个月,因此将%m更新为%B
last_month.strftime("%Y, %B")