一般的に、あなたは今答えを手に入れましたが、多分私が作成した私のクラスも役に立ちます。私にとっては、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") -ここで、プロジェクトで使用するタイムゾーンを定義します
GetDate("2019-08-08").current()-これにより、文字列の日付がpt 1で定義したタイムゾーンで時間認識オブジェクトに変換されます。デフォルトの文字列形式はformat="%Y-%m-%d"自由に変更できます。(例GetDate("2019-08-08 08:45", format="%Y-%m-%d %H:%M").current())
GetDate("2019-08-08").get_month_first_day() 指定された日付(文字列またはオブジェクト)の月の初日を返します
GetDate("2019-08-08").get_month_last_day() 指定された日付の月の最終日を返します
GetDate("2019-08-08").minimum_time() 指定された日付の開始日を返します
GetDate("2019-08-08").maximum_time() 与えられた日付の日の終わりを返します
GetDate("2019-08-08").time_delta_days({number_of_days})指定された日付を返し、{日数}を追加します(次のように呼び出すこともできます:GetDate(timezone.now()).time_delta_days(-1)昨日)
GetDate("2019-08-08").time_delta_haours({number_of_hours}) pt 7に似ていますが、何時間も取り組んでいます
GetDate("2019-08-08").time_delta_seconds({number_of_seconds}) pt 7に似ていますが、秒単位で動作します
name 'timedelta' is not defined、それはtimedeltaどこにも定義されていないことを意味します。Pythonは通常、そのエラーメッセージについてかなり有益です。