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

当前回答

如果你碰巧已经在使用熊猫,你可以通过不指定格式来节省一点空间:

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

其他回答

试试这个:

在当前日期上增加5天。

from datetime import datetime, timedelta

current_date = datetime.now()
end_date = current_date + timedelta(days=5) # Adding 5 days.
end_date_formatted = end_date.strftime('%Y-%m-%d')
print(end_date_formatted)

从当前日期减去5天。

from datetime import datetime, timedelta

current_date = datetime.now()
end_date = current_date + timedelta(days=-5) # Subtracting 5 days.
end_date_formatted = end_date.strftime('%Y-%m-%d')
print(end_date_formatted)

首先导入timedelta和date。

from datetime import timedelta, date

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

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

我猜你错过了一些类似的东西:

from datetime import timedelta

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

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

import datetime

然后使用datetime.timedelta:

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

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