Python-从给定日期减去5天不能正常工作
我有一个定义,它接收一个字符串作为输入(例如2013年6月1日),并在从输入日期减去5天后返回一个字符串。如果日期是在月底,这似乎不能正常工作Python-从给定日期减去5天不能正常工作,python,Python,我有一个定义,它接收一个字符串作为输入(例如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日”,我预计的产出为“201
def GetEffectiveDate(self, systemdate):
return datetime.strftime(datetime.strptime(systemdate, '%d %B %Y') - timedelta(days = 5), '%d/%b/%Y')
例如,如果输入为“2013年6月1日”,我预计的产出为“2013年5月27日”,但其返回的是“2013年6月27日”。不知道我做错了什么 至少根据您的输入,您的格式字符串不正确。将输出从
'%d/%b/%Y'
更改为'%d/%b/%Y'
return datetime.strftime(datetime.strptime(systemdate, '%d %B %Y') - timedelta(days = 5), '%d/%B/%Y')
正如您在Python 2.7中所期望的那样,它适用于我: 系统日期='2013年6月1日' datetime.datetime.strftime(datetime.datetime.strptime(系统日期,'%d%B%Y')-datetime.timedelta(天=5),'%d/%B/%Y')) “2013年5月27日” 在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
。。。正如所料。谢谢。我试过了,但仍然没有改变月份。请在编辑后立即尝试。我复制并粘贴了你的代码,它对我很好。。。