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