我使用current\u month变量来查询数据,但这里有一个问题-如果一个月中的某一天晚于15号,我想将当前月份设置为下一个月。因此,2016年4月16日的当月应为2016年5月1日。我有代码可以工作,但它不觉得python。如有建议,将不胜感激。你知道吗
month = datetime.datetime.now().strftime("%m")
year = datetime.datetime.now().strftime("%Y")
day = datetime.datetime.now().strftime("%d")
#Check if day in the month is past 15th if so set current month
if int(day) > 15:
if int(month) < 9: # check if the month in 1-9 if so pad leading zero
x = int(month)+1
current_month = year+"-0"+str(x)+"-01"
if int(month) == 9: # check if the month in 1-9 if so pad leading zero
x = int(month)+1
current_month = year+"-"+str(x)+"-01"
elif int(month) == 12: # check if the month is Dec if so roll to the next year and set month to Jan
month = "01"
y = int(year)+1
current_month = str(y)+"-"+month+"-01"
else:
x = int(month)+1 # just add one to the month if months are 10 or 11
current_month = year+"-"+str(x)+"-01"
else:
current_month = year+"-"+month+"-01" #prior to the 15'th so just use normal year, month and day
Scott方法的另一个替代方法(它非常有效,您可能应该接受它)是使用^{} :
结果是:
感谢Scott指出了为什么我最初的方法是不必要的复杂(而且是错误的)。你知道吗
相关问题 更多 >
编程相关推荐