确定在第15天-python 2.7之后滚动到下个月的当前月份变量

时间:2016-04-15 23:59:23

标签: python datetime

我使用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

2 个答案:

答案 0 :(得分:2)

# 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")

答案 1 :(得分:0)

斯科特方法的替代方法(效果非常好并且您应该接受它)是使用dateutil.relativedelta

from datetime import datetime
from dateutil.relativedelta import relativedelta

def next_month_after_day(dt, trans_day=15):
    rd = relativedelta(months=(dt.day > trans_day), day=1)

    return dt + rd

dt1 = datetime(1996, 2, 3)
dt2 = datetime(1996, 2, 15)
dt3 = datetime(1996, 2, 16)
dt4 = datetime(1996, 12, 18)

fmt = "%Y-%m-%d"
for x in (dt1, dt2, dt3, dt4):
    dt_before = x
    dt_after = next_month_after_day(x)
    print('{} -> {}'.format(dt_before.strftime(fmt), dt_after.strftime(fmt)))

结果是:

1996-02-03 -> 1996-02-01
1996-02-15 -> 1996-02-01
1996-02-16 -> 1996-03-01
1996-12-18 -> 1997-01-01

感谢斯科特指出为什么我的原始方法不必要地复杂(和错误)。