在日期中循环

时间:2018-11-15 20:53:24

标签: python

我在代码的上一部分中定义了日期和月份。我需要该程序在一天少于7天时运行。我要求输入过去7天的支出。

问题:如果day的输入是4,例如4-4(days)是第0天(不存在),4-5是-1天,4-6是-2,4- 7是-3天。我需要它是4-4 = 31或30或28或29天(已经定义),4-5 = 30、4-6 = 29。

我知道这结构不好,我很抱歉,英语不是我的母语。如果不这样理解,将尝试弄清楚。

listOfSpendings = []
x = 0
while x < 7:
    if day - x <=0:
        month = month - 1
        dayDiff= ###SOMETHING I DUNNOOOO
        day = monthlenght - dayDiff
    print ("How many liters did you spend on the day", day - x, "of", month)
    spendings = input()
    while True:
        try:
            spendings = int(spendings)
            if spendings < 0:
                spendings = input ("Insert a value =! 0")
            else:
                break
        except ValueError:
            spendings = input("Incorrect value, correct")
    x = x+1
    listOfSpendings.append(spendings)

sumSpendings = sum (listOfSpendings)

2 个答案:

答案 0 :(得分:2)

您的代码原本也将与几个月成负数。使用建议的日期时间库,您可以执行以下操作:

from datetime import datetime, timedelta

list_of_spendings = []

# Month number
for day in [(datetime.now()-timedelta(x)) for x in range(7)]:
    print('How many liters did you spend on the day {} of {}'.format(day.day, day.month))
    #Rest of your code

OR

# Month name
for day in [(datetime.now()-timedelta(x)) for x in range(7)]:
    print('How many liters did you spend on the day {} of {}'.format(day.day, day.strftime('%B')))
    #Rest of your code

OR

# Short month name
for day in [(datetime.now()-timedelta(x)) for x in range(7)]:
    print('How many liters did you spend on the day {} of {}'.format(day.day, day.strftime('%b')))
    #Rest of your code

答案 1 :(得分:0)

这就是我的想法。预先定义了“ Dia”和“ mes”。

翻译:

listaGastos = listOfSpendings
gastos = spendings
dia = day
mes = month
DuracMes = monthlenght
diaC = currentDay
mesC = currentMonth

代码:

DuracMes = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
listaGastos = []
x = 0
diaC = dia
mesC = mes
while x < 7:
    dia = diaC - x
    if dia <= 0:
        mes = mesC - 1
        diaDif = diaC - 1
        dia = DuracMes [mes - 1] + dia
    print("Quantos litros de soro fisiologico foram gastos no dia", dia, "de", mes)
    gastos = input()
    while True:
        try:
            gastos = int (gastos)
            if gastos < 0:
                gastos = input ("Introduza um valor diferente de 0: ")
            else:
                break
        except ValueError:
            gastos = input ("Nao inseriu um valor adequado, quantos litros de soro fisiologico foram gastos nos ultimos sete dias? ")
    x += 1
    listaGastos.append(gastos)

sumGastos = sum (listaGastos)