我试图以2016年7月的格式获得上个月和当年。
我已经尝试过(但是没有用)并且它不会打印7月,而是数字:
import datetime
now = datetime.datetime.now()
print now.year, now.month(-1)
答案 0 :(得分:18)
如果您正在操作日期,那么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')
给你:
'July 2016'
答案 1 :(得分:6)
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]
答案 2 :(得分:1)
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
答案 3 :(得分:1)
使用Pandas的替代解决方案,将今天转换为月度期,然后减去一个月(月)。使用strftime
转换为所需格式。
import datetime as dt
import pandas as pd
>>> (pd.Period(dt.datetime.now(), 'M') - 1).strftime('%B %Y')
u'July 2016'
答案 4 :(得分:0)
您可以仅使用Python日期时间库来实现此目的。
说明:
import datetime as dt
format(dt.date.today().replace(day=1) - dt.timedelta(days=1), '%B %Y')
>>>'June-2019'
答案 5 :(得分:0)
import datetime as dt
last_month = dt.datetime.today().replace(day=1) - dt.timedelta(1)
last_month.strftime("%Y, %B")
答案 6 :(得分:0)
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
答案 7 :(得分:-1)
from datetime import date, datetime, timedelta
last_month = date.today().replace(day=1) - timedelta(1)
last_month.strftime("%Y%m")