我有这个定义,它接收一个字符串作为输入(例如2013年6月1日),并在从输入日期减去5天后返回一个字符串。如果日期是在月末,这似乎不能正常工作。
def GetEffectiveDate(self, systemdate):
return datetime.strftime(datetime.strptime(systemdate, '%d %B %Y') - timedelta(days = 5), '%d/%b/%Y')
例如,如果输入为'2013年6月1日',我预计的输出为'27 / May / 2013',但其返回'27 / June / 2013'。不知道我在这里做错了什么。
答案 0 :(得分:2)
您的格式字符串不正确,至少根据您的输入。将您的输出从'%d/%b/%Y'
更改为'%d/%B/%Y'
return datetime.strftime(datetime.strptime(systemdate, '%d %B %Y') - timedelta(days = 5), '%d/%B/%Y')
答案 1 :(得分:0)
对你来说,正如你在Python 2.7中所期望的那样:
systemdate =' 2013年6月1日'
datetime.datetime.strftime(datetime.datetime.strptime(systemdate,'%d%B%Y') - datetime.timedelta(days = 5),'%d /%b /%Y&#39)
' 27 /月/ 2013'
答案 2 :(得分:0)
在Python 3.3中:
from datetime import timedelta, datetime
def GetEffectiveDate(systemdate):
return datetime.strftime(datetime.strptime(systemdate, '%d %b %Y') -
timedelta(days = 5), '%d/%b/%Y')
print(GetEffectiveDate("1 June 2013"))
...产生以下错误:
ValueError: time data '1 June 2013' does not match format '%d %b %Y'
...而改变@Bryan Moyles建议的格式代码:
def GetEffectiveDate(systemdate):
return datetime.strftime(datetime.strptime(systemdate, '%d %B %Y') -
timedelta(days = 5), '%d/%b/%Y')
...生产:
27/May/2013
......正如所料。