1. 程式人生 > >python字串'2018-11-14 00:00:00'轉時間戳,並獲取下個月同一時間

python字串'2018-11-14 00:00:00'轉時間戳,並獲取下個月同一時間

需求,在資料庫篩選從2018-11-14 00:00:00-2018-12-14 00:00:00一個月的資料

str_time ='2018-12-14 00:00:00'
start_date = datetime.datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S")
print  start_date

結果:
datetime.datetime(2018, 11, 14, 0, 0)
def get_next_month_first_day(date):
    month = date.month - 1 + 1
    year = date.year + month / 12
    #下個月+1,上個月-1
    month = month % 12 + 1
    return date.replace(year=year, month=month, day=1)
    
end_date = get_next_month_first_day(start_date)
print  end_date 

結果:
datetime.datetime(2018, 12, 14, 0, 0)
 result = Book.objects.filter(start_date__gte=start_date,end_date__lte=end_date)