Create a Python class that supports date addition and subtraction
We will create a Python classDate, this class supports date addition and subtraction. We will usedatetimemodule to handle date addition and subtraction, and ensure the date format is correct.
Example
from datetime import datetime, timedelta
class Date:
def __init__(self, year, month, day):
self.date = datetime(year, month, day)
def __add__(self, days):
new_date = self.date + timedelta(days=days)
return Date(new_date.year, new_date.month, new_date.day)
def __sub__(self, days):
new_date = self.date - timedelta(days=days)
return Date(new_date.year, new_date.month, new_date.day)
def __str__(self):
return self.date.strftime('%Y-%m-%d')
# Example usage
date = Date(2023, 10, 1)
print("Initial date:", date)
date_plus_10 = date + 10
print("Date after adding 10 days:", date_plus_10)
date_minus_5 = date - 5
print("Date after subtracting 5 days:", date_minus_5)
class Date:
def __init__(self, year, month, day):
self.date = datetime(year, month, day)
def __add__(self, days):
new_date = self.date + timedelta(days=days)
return Date(new_date.year, new_date.month, new_date.day)
def __sub__(self, days):
new_date = self.date - timedelta(days=days)
return Date(new_date.year, new_date.month, new_date.day)
def __str__(self):
return self.date.strftime('%Y-%m-%d')
# Example usage
date = Date(2023, 10, 1)
print("Initial date:", date)
date_plus_10 = date + 10
print("Date after adding 10 days:", date_plus_10)
date_minus_5 = date - 5
print("Date after subtracting 5 days:", date_minus_5)
Code explanation:
__init__Method: initializationDateThe class accepts year, month, and day as parameters and converts them todatetimeobjects.__add__Method: overload the addition operator+, allows a date object to be added with a number of days, returning a newDateobject.__sub__Method: overload the subtraction operator-, allows a date object to subtract a number of days, returning a newDateobject.__str__Method: override the string representation method, returns the formatted string of the date.
Output result:
初始日期: 2023-10-01 加 10 天后的日期: 2023-10-11 减 5 天后的日期: 2023-09-26Other extensions
Python3 Examples