我使用current_month变量查询数据,但这是捕获的问题-如果该月中的某天晚于15日,则要将当前月份设置为下个月。因此,2016年4月16日的当前月份应为2016年5月1日。我有能正常工作的代码,但感觉不到pythonic。建议将不胜感激。

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

最佳答案

# Get today's date/time
today = datetime.datetime.now()
# add 16 days if after the 15th
if today.day > 15:
    today += datetime.timedelta(16)
# Format that date w/ day being 1
current_month = today.strftime("%Y-%m-01")

08-24 18:24