我有一个日期“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")

打印日期->正在打印'2011-10-10 00:00:00'

现在我想在这个日期上加5天。我使用了以下代码:

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

返回以下错误:

name 'timedelta' is not defined

当前回答

这可能会有帮助:

from datetime import date, timedelta
date1 = date(2011, 10, 10)
date2 = date1 + timedelta(days=5)
print (date2)

其他回答

首先导入timedelta和date。

from datetime import timedelta, date

date.today()将返回今天的日期时间,然后你可以给它添加一个timedelta:

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

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

import datetime

然后使用datetime.timedelta:

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

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

有时我们需要使用从日期到日期的搜索。如果使用date__range,则需要给to_date加上1天,否则queryset将为空。

例子:

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

如果现在想要添加日期,可以使用这段代码

from datetime import datetime
from datetime import timedelta


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

一般来说,你现在已经有了一个答案,但也许我创建的类也会有帮助。对我来说,它解决了我在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)

如何使用

self.tz = pytz.timezone("Europe/Warsaw") - here you define Time Zone you want to use in project 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()) GetDate("2019-08-08").get_month_first_day() returns given date (string or object) month first day GetDate("2019-08-08").get_month_last_day() returns given date month last day GetDate("2019-08-08").minimum_time() returns given date day start GetDate("2019-08-08").maximum_time() returns given date day end 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) GetDate("2019-08-08").time_delta_haours({number_of_hours}) similar to pt 7 but working on hours GetDate("2019-08-08").time_delta_seconds({number_of_seconds}) similar to pt 7 but working on seconds