2016-04-15 3 views
1

データをクエリするためにcurrent_month変数を使用しますが、ここではキャッチがあります。月の日が15日後であれば、現在の月を翌月とする。したがって、2011年4月16日の現在の月は2011年5月1日である必要があります。私は動作するコードを持っていますが、pythonicを感じません。提案をいただければ幸いです。15日後の次の月にロールオーバーする現在の月変数を調べる - python 2.7

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 
+0

現在の日付に16日を追加して1日に設定することはできませんか? –

+1

@ScottHunter:月の数が異なるため、日数を加算することが不正確になることがあります。 15日を引いた後、1日を1にして1ヶ月を追加すると正確になります。 – zondo

+0

@zondo:調整が必要な場合にのみ行うか、 –

答えて

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") 
+0

優雅な解決策!ありがとうございました@ScottHunter –

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 

私の元のアプローチが不必要に複雑で(そして間違っている)理由を指摘してくれたScottに感謝します。

+0

私はその日が何であれ1でなければならないと考えました。問題は、正しい月を得る方法でした。 –

+0

@ScottHunterよろしくお願いします。一定。 – Paul

+0

私はあなたが12月の場合はテストしなかったと思います。 –

関連する問題