Añadir 5 días a una fecha en Python


Tengo una fecha "10/10/11(m-d-y)" y quiero agregarle 5 días usando un script Python. Por favor considere una solución general que funciona en el mes termina también.

Estoy usando el siguiente código:

import re
from datetime import datetime

StartDate = "10/10/11"

Date = datetime.strptime(StartDate, "%m/%d/%y")

print Date -> está imprimiendo '2011-10-10 00:00:00'

Ahora quiero agregar 5 días a esta fecha. Usé el siguiente código:

EndDate = Date.today()+timedelta(days=10)

Que devolvió este error:

name 'timedelta' is not defined
Author: gary, 2011-07-29

9 answers

Las respuestas anteriores son correctas, pero generalmente es una mejor práctica:

import datetime

Entonces tendrás, usando datetime.timedelta:

date_1 = datetime.datetime.strptime(start_date, "%m/%d/%y")

end_date = date_1 + datetime.timedelta(days=10)
 381
Author: Botond Béres,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-25 09:43:21

Primero importa timedelta.

from datetime import timedelta

Y Date.today() devolverá la fecha y hora de hoy, puede ser que desee

EndDate = Date + timedelta(days=10)
 90
Author: DrTyrsa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-29 09:20:23

Supongo que te estás perdiendo algo así:

from datetime import timedelta
 11
Author: vstm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-29 09:20:48

Si ya está usando pandas, puede ahorrar un poco de espacio al no especificar el formato:

import pandas as pd
startdate = "10/10/2011"
enddate = pd.to_datetime(startdate) + pd.DateOffset(days=5)
 10
Author: fantabolous,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-29 14:10:19

Aquí hay otro método para agregar días en fecha usando relativedelta de dateutil.

from datetime import datetime
from dateutil.relativedelta import relativedelta

print 'Today: ',datetime.now().strftime('%d/%m/%Y %H:%M:%S') 
date_after_month = datetime.now()+ relativedelta(days=5)
print 'After 5 Days:', date_after_month.strftime('%d/%m/%Y %H:%M:%S')

Salida:

Hoy: 25/06/2015 15:56:09

Después de 5 Días: 30/06/2015 15:56:09

 10
Author: Atul Arvind,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-25 12:56:53

Aquí hay una función de obtener a partir de ahora + días especificados

import datetime

def get_date(dateFormat="%d-%m-%Y", addDays=0):

    timeNow = datetime.datetime.now()
    if (addDays!=0):
        anotherTime = timeNow + datetime.timedelta(days=addDays)
    else:
        anotherTime = timeNow

    return anotherTime.strftime(dateFormat)

Uso:

addDays = 3 #days
output_format = '%d-%m-%Y'
output = get_date(output_format, addDays)
print output
 7
Author: Guray Celik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-14 08:17:45

Para tener un código menos detallado , y evitar conflictos de nombres entre datetime y datetime.datetime, debe cambiar el nombre de las clases con camelCase nombres.

from datetime import datetime as DateTime, timedelta as TimeDelta

Así que puedes hacer lo siguiente, lo cual creo que está claro.

date_1 = DateTime.today() 
end_date = date_1 + TimeDelta(days=10)

Además, no habría ningún conflicto de nombres si quieres import datetime más adelante.

 3
Author: toto_tico,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-27 10:42:31

Si desea agregar días hasta la fecha ahora, puede usar este código

from datetime import datetime
from datetime import timedelta


date_now_more_5_days = (datetime.now() + timedelta(days=5) ).strftime('%Y-%m-%d')
 3
Author: Jorge Omar Martinez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-20 19:51:33

Este es mi desarrollo inicial pero más completo para una función dateadd genérica en python

import datetime
from dateutil.relativedelta import relativedelta

def dateadd(date, part ,value):

    if part=='year':
        result = date + (value * relativedelta(years = 1))
    elif part == 'month':
        result = date + (value * relativedelta(months = 1))
    elif part == 'day':
        result = date + (value * relativedelta(days = 1))
    elif part == 'hour':
        result = date + (value * relativedelta(hours = 1))
    elif part == 'minute':
        result = date + (value * relativedelta(minutes = 1))
    elif part == 'second':
        result = date + (value * relativedelta(seconds = 1))
    return result


date = datetime.datetime.now()
print(date, "now")
print(dateadd(date,'year',2)   ,"year',2", )
print(dateadd(date,'year',-2)  ,"year',-2", )
print(dateadd(date,'month',2)  ,"month',2", )
print(dateadd(date,'month',-2) ,"month',-2", )
print(dateadd(date,'day',2)    ,"day',2", )
print(dateadd(date,'day',-2)   ,"day',-2", )
print(dateadd(date,'hour',2)   ,"hour',2", )
print(dateadd(date,'hour',-2)  ,"hour',-2", )
print(dateadd(date,'minute',2) ,"minute',2", )
print(dateadd(date,'minute',-2),"minute',-2", )
print(dateadd(date,'second',2) ,"second',2", )
print(dateadd(date,'second',-2),"second',-2", )

Resultado:
2018-03-08 09:04: 12.619699 ahora
2020-03-08 09:04: 12.619699 año',2
2016-03-08 09: 04: 12.619699 año', -2
2018-05-08 09:04: 12.619699 mes', 2
2018-01-08 09: 04: 12.619699 mes', -2
2018-03-10 09:04: 12.619699 día', 2
2018-03-06 09:04: 12.619699 día', -2
2018-03-08 11:04: 12.619699 hora', 2
2018-03-08 07:04: 12.619699 hora',-2
2018-03-08 09:06: 12.619699 minuto', 2
2018-03-08 09: 02: 12.619699 minuto', -2
2018-03-08 09:04: 14.619699 segundo', 2
2018-03-08 09: 04: 10.619699 segundo', -2

 0
Author: gafajardog,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-08 14:20:19