在Python中为日期添加5天

问题:在Python中为日期添加5天

我有一个日期"10/10/11(m-d-y)",我想使用Python脚本为其添加5天。请考虑在月底也可以使用的一般解决方案。

我正在使用以下代码:

import re
from datetime import datetime

StartDate = "10/10/11"

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

print Date ->正在打印 '2011-10-10 00:00:00'

现在,我想在此日期之前增加5天。我使用以下代码:

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

哪个返回此错误:

name 'timedelta' is not defined

I have a date "10/10/11(m-d-y)" and I want to add 5 days to it using a Python script. Please consider a general solution that works on the month ends also.

I am using following code:

import re
from datetime import datetime

StartDate = "10/10/11"

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

print Date -> is printing '2011-10-10 00:00:00'

Now I want to add 5 days to this date. I used the following code:

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

Which returned this error:

name 'timedelta' is not defined

回答 0

先前的答案是正确的,但是通常这样做是更好的做法:

import datetime

然后,您将拥有datetime.timedelta

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

end_date = date_1 + datetime.timedelta(days=10)

The previous answers are correct but it’s generally a better practice to do:

import datetime

Then you’ll have, using datetime.timedelta:

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

end_date = date_1 + datetime.timedelta(days=10)

回答 1

导入timedeltadate首先。

from datetime import timedelta, date

date.today()会返回今天的日期时间,可能是您想要的

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

Import timedelta and date first.

from datetime import timedelta, date

And date.today() will return today’s datetime, may be you want

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

回答 2

如果您碰巧已经在使用pandas,则可以通过不指定格式来节省一些空间:

import pandas as pd
startdate = "10/10/2011"
enddate = pd.to_datetime(startdate) + pd.DateOffset(days=5)

If you happen to already be using pandas, you can save a little space by not specifying the format:

import pandas as pd
startdate = "10/10/2011"
enddate = pd.to_datetime(startdate) + pd.DateOffset(days=5)

回答 3

我想您缺少这样的东西:

from datetime import timedelta

I guess you are missing something like that:

from datetime import timedelta

回答 4

这是另一种使用dateutil的relativedelta添加日期的方法。

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')

输出:

今天:25/06/2015 15:56:09

5天后:30/06/2015 15:56:09

Here is another method to add days on date using dateutil’s relativedelta.

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')

Output:

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

After 5 Days: 30/06/2015 15:56:09


回答 5

如果要立即添加日期,可以使用此代码

from datetime import datetime
from datetime import timedelta


date_now_more_5_days = (datetime.now() + timedelta(days=5) ).strftime('%Y-%m-%d')

If you want add days to date now, you can use this code

from datetime import datetime
from datetime import timedelta


date_now_more_5_days = (datetime.now() + timedelta(days=5) ).strftime('%Y-%m-%d')

回答 6

这是从现在开始+指定天数的功能

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)

用法:

addDays = 3 #days
output_format = '%d-%m-%Y'
output = get_date(output_format, addDays)
print output

Here is a function of getting from now + specified days

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)

Usage:

addDays = 3 #days
output_format = '%d-%m-%Y'
output = get_date(output_format, addDays)
print output

回答 7

为了减少冗长的代码,并避免datetime和datetime.datetime之间的名称冲突 ,应使用CamelCase名称重命名这些类。

from datetime import datetime as DateTime, timedelta as TimeDelta

因此,您可以执行以下操作,我认为这更清楚。

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

另外,如果您以后想要的话,也不会出现名称冲突import datetime

In order to have have a less verbose code, and avoid name conflicts between datetime and datetime.datetime, you should rename the classes with CamelCase names.

from datetime import datetime as DateTime, timedelta as TimeDelta

So you can do the following, which I think it is clearer.

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

Also, there would be no name conflict if you want to import datetime later on.


回答 8

使用timedeltas可以做到:

import datetime
today=datetime.date.today()


time=datetime.time()
print("today :",today)

# One day different .
five_day=datetime.timedelta(days=5)
print("one day :",five_day)
#output - 1 day , 00:00:00


# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)


# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)
#output - 
today : 2019-05-29
one day : 5 days, 0:00:00
fitfthday 2019-06-03

using timedeltas you can do:

import datetime
today=datetime.date.today()


time=datetime.time()
print("today :",today)

# One day different .
five_day=datetime.timedelta(days=5)
print("one day :",five_day)
#output - 1 day , 00:00:00


# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)


# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)
#output - 
today : 2019-05-29
one day : 5 days, 0:00:00
fitfthday 2019-06-03

回答 9

通常,您现在没有答案,但是也许我创建的我的类也会有所帮助。对我来说,它可以解决我在Pyhon项目中曾经遇到的所有要求。

class GetDate:
    def __init__(self, date, format="%Y-%m-%d"):
        self.tz = pytz.timezone("Europe/Warsaw")

        if isinstance(date, str):
            date = datetime.strptime(date, format)

        self.date = date.astimezone(self.tz)

    def time_delta_days(self, days):
        return self.date + timedelta(days=days)

    def time_delta_hours(self, hours):
        return self.date + timedelta(hours=hours)

    def time_delta_seconds(self, seconds):
        return self.date + timedelta(seconds=seconds)

    def get_minimum_time(self):
        return datetime.combine(self.date, time.min).astimezone(self.tz)

    def get_maximum_time(self):
        return datetime.combine(self.date, time.max).astimezone(self.tz)

    def get_month_first_day(self):
        return datetime(self.date.year, self.date.month, 1).astimezone(self.tz)

    def current(self):
        return self.date

    def get_month_last_day(self):
        lastDay = calendar.monthrange(self.date.year, self.date.month)[1]
        date = datetime(self.date.year, self.date.month, lastDay)
        return datetime.combine(date, time.max).astimezone(self.tz)

如何使用它

  1. self.tz = pytz.timezone("Europe/Warsaw") -在此处定义要在项目中使用的时区
  2. GetDate("2019-08-08").current()-这会将您的字符串日期转换为具有您在pt 1中定义的时区的时间敏感对象。默认字符串格式为,format="%Y-%m-%d"但可以随时更改。(例如。GetDate("2019-08-08 08:45", format="%Y-%m-%d %H:%M").current()
  3. GetDate("2019-08-08").get_month_first_day() 返回给定日期(字符串或对象)月份的第一天
  4. GetDate("2019-08-08").get_month_last_day() 返回上个月的给定日期
  5. GetDate("2019-08-08").minimum_time() 返回给定日期的开始日期
  6. GetDate("2019-08-08").maximum_time() 返回给定日期的一天结束
  7. GetDate("2019-08-08").time_delta_days({number_of_days})返回给定的日期+添加{天数}(您也可以调用:GetDate(timezone.now()).time_delta_days(-1)昨天)
  8. GetDate("2019-08-08").time_delta_haours({number_of_hours}) 与pt 7类似,但工作时间较长
  9. GetDate("2019-08-08").time_delta_seconds({number_of_seconds}) 类似于pt 7,但工作几秒钟

Generally you have’got an answer now but maybe my class I created will be also helpfull. For me it solves all my requirements I have ever had in my Pyhon projects.

class GetDate:
    def __init__(self, date, format="%Y-%m-%d"):
        self.tz = pytz.timezone("Europe/Warsaw")

        if isinstance(date, str):
            date = datetime.strptime(date, format)

        self.date = date.astimezone(self.tz)

    def time_delta_days(self, days):
        return self.date + timedelta(days=days)

    def time_delta_hours(self, hours):
        return self.date + timedelta(hours=hours)

    def time_delta_seconds(self, seconds):
        return self.date + timedelta(seconds=seconds)

    def get_minimum_time(self):
        return datetime.combine(self.date, time.min).astimezone(self.tz)

    def get_maximum_time(self):
        return datetime.combine(self.date, time.max).astimezone(self.tz)

    def get_month_first_day(self):
        return datetime(self.date.year, self.date.month, 1).astimezone(self.tz)

    def current(self):
        return self.date

    def get_month_last_day(self):
        lastDay = calendar.monthrange(self.date.year, self.date.month)[1]
        date = datetime(self.date.year, self.date.month, lastDay)
        return datetime.combine(date, time.max).astimezone(self.tz)

How to use it

  1. self.tz = pytz.timezone("Europe/Warsaw") – here you define Time Zone you want to use in project
  2. GetDate("2019-08-08").current() – this will convert your string date to time aware object with timezone you defined in pt 1. Default string format is format="%Y-%m-%d" but feel free to change it. (eg. GetDate("2019-08-08 08:45", format="%Y-%m-%d %H:%M").current())
  3. GetDate("2019-08-08").get_month_first_day() returns given date (string or object) month first day
  4. GetDate("2019-08-08").get_month_last_day() returns given date month last day
  5. GetDate("2019-08-08").minimum_time() returns given date day start
  6. GetDate("2019-08-08").maximum_time() returns given date day end
  7. GetDate("2019-08-08").time_delta_days({number_of_days}) returns given date + add {number of days} (you can also call: GetDate(timezone.now()).time_delta_days(-1) for yesterday)
  8. GetDate("2019-08-08").time_delta_haours({number_of_hours}) similar to pt 7 but working on hours
  9. GetDate("2019-08-08").time_delta_seconds({number_of_seconds}) similar to pt 7 but working on seconds

回答 10

有时我们需要使用按日期和日期进行搜索。如果我们使用date__range,那么我们需要添加1天和to_date,否则queryset将为空。

例:

从datetime导入timedelta

from_date = parse_date(request.POST [‘from_date’])

to_date = parse_date(request.POST [‘to_date’])+ timedelta(days = 1)

Attenance_list = models.DailyAttendance.objects.filter(attdate__range = [from_date,to_date])

Some time we need to use searching by from date & to date. If we use date__range then we need to add 1 days with to_date otherwise queryset will empty.

Example:

from datetime import timedelta

from_date = parse_date(request.POST[‘from_date’])

to_date = parse_date(request.POST[‘to_date’]) + timedelta(days=1)

attendance_list = models.DailyAttendance.objects.filter(attdate__range = [from_date, to_date])