Increase days to a given date with nested arrangement


I am a beginner in Python and I am trying to make a program that reads a date ( AAAA-MM-DD ) given by the user and allows me to show 5 days subsequent to the given date and to make the changes of day, month or year in his case Any ideas? I got stuck there.

This is my code, I do not know if it is the most optimal, but it is a part of what I want to do:

fecha=input("Introduce una fecha:")





if mes==1 or mes==3 or mes==5 or mes==7 or mes==8 or mes==10 or mes==12:
elif mes==2:
    if (anio % 4 == 0 and anio % 100 != 0 or anio % 400 == 0):
elif mes==4 or mes==6 or mes==9 or mes==11:
asked by Chely 10.01.2018 в 19:52

3 answers


There are multiple ways to approach the problem as usual, based on what you already have I would consider first validating the date, if the date entered is not valid the rest does not make sense. Done this we can raise a very simple algorithm considering that we are only going to add up to 5 days (so we are only going to move between two months at the most):

  • If the day of the month plus the number of days increased is less than the maximum number of days we simply add the days.

  • If the above is not fulfilled we must add one a month with the proviso that if we are in December the month will become January and we add one a year. The day of the new date will be the days that exceed the maximum of days of the month.

The code might look something like this, if I have not screwed up somewhere:

def cinco_dias(fecha):
    año, mes, dia = (int(n) for n in fecha.split("-"))

    if año < 1 or not isinstance(año, int):
        raise ValueError("El año debe ser un entero mayor de 0")

    if mes in (1, 3, 5, 7, 8, 10, 12):
        dias_mes = 31

    elif mes == 2:
        if año % 4 == 0 and (año % 100 != 0 or año % 400 == 0):
            dias_mes = 29
            dias_mes = 28

    elif mes in (4, 6, 9, 11):
        dias_mes = 30

        raise ValueError("El mes debe ser un entero entre 1 y 12 incluidos")

    if not 1 <= dia <= dias_mes:
        raise ValueError("{} no es un día válido para el {:04d}/{:02d}".format(dia, año, mes))

    dias = []
    for n in range(1, 6):
        if dia + n <= dias_mes:
            dias.append('{:04d}-{:02d}-{:02d}'.format(año, mes, dia + n))
            if mes != 12:
                dias.append('{:04d}-{:02d}-{:02d}'.format(año, mes+1, n - (dias_mes - dia)))
                dias.append('{:04d}-01-{:02d}'.format(año + 1, n - (dias_mes - dia)))

    return dias

fecha = input("Introduce una fecha: ")

Examples of departures:

Introduce una fecha: 2020-02-27
['2020-02-28', '2020-02-29', '2020-03-01', '2020-03-02', '2020-03-03']

Introduce una fecha: 2018-12-29
['2018-12-30', '2018-12-31', '2019-01-01', '2019-01-02', '2019-01-03']

Introduce una fecha: 2023-02-29
Traceback (most recent call last):
  File "", line 38, in <module>
  File "", line 23, in cinco_dias
    raise ValueError("{} no es un día válido para el {}/{}".format(dia, mes, año))
ValueError: 29 no es un día válido para el 2023/02

Introduce una fecha: 2018-04-31
Traceback (most recent call last):
  File "", line 38, in <module>
  File "", line 23, in cinco_dias
    raise ValueError("{} no es un día válido para el {:04d}/{:02d}".format(dia, año, mes))
ValueError: 31 no es un día válido para el 2018/04

It should be noted that the above does not make much sense, except in academic or recreational settings, when Python already provides this functionality thanks to the datetime module and the datetime.timedelta method:

import datetime

def añadir_dias(fecha, dias):
    fecha = datetime.datetime.strptime(fecha, "%Y-%m-%d")
    fechas = [datetime.datetime.strftime(fecha + datetime.timedelta(days=d), "%Y-%m-%d")
                  for d in range(1, días + 1)]
    return fechas

fecha = input("Introduce una fecha: ")
print(añadir_dias(fecha), 5)
answered by 10.01.2018 в 21:30

Unless you have some restriction on the type of solution, I think this is the simplest thing you can do:

from datetime import timedelta, date

fecha_ingreso = input("Introduce una fecha:")
d,m,a = [int(v) for v in fecha_ingreso.split("-")]

fecha = date(a, m, d)
for i in range(1,6):
  newdate = fecha + timedelta(days=i)
  • We rely on the base module datetime
  • First of all, it is not necessary to manage a list for the entered values, doing: d,m,a = [int(v) for v in fecha_ingreso.split("-")] , we separate the entered values, we convert them to integers and assign them to three variables for each part of the date
  • We create a date object by date(a, m, d) that will represent the entered date
  • As you ask to show the next 5 dates subsequent to the one entered, you can cycle using range(1,6) that will go from 1 to 5.
  • Within the cycle we use a timedelta() object that basically represents a duration, in this case of days, and that helps us to do date arithmetic in a simple way, in this case newdate = fecha + timedelta(days=i) which will increase the entered date by one day.
  • Finally, we print the date on the screen using strftime() that allows us to format it properly
answered by 10.01.2018 в 21:24

There are dates management functions that help you and allow you to operate with dates by performing the conversion that you explain yourself. In your case it would be:

from datetime import datetime, timedelta

# Formateamos la fecha según el formato especificado en la cadena
# Si la fecha es día/mes/año, en vez de '%Y-%m-%d' debe ser '%d-%m-%Y'
fecha = datetime.strptime(fecha, '%Y-%m-%d').date()

# Añadimos 5 días (con timedelta)
nueva_fecha = fecha + timedelta(days=5)

# Convertimos en string de nuevo

If date is equal to '2017-12-29' of returns '2018-01-03'.

Check out the documentation of datetime and time management in Python to learn more What you are doing. Among other things you will see how to format dates entered in day / month / year format, because the example I show you is in the year / month / day format.


answered by 10.01.2018 в 21:25