Create a Python Class Supporting Date Addition and Subtraction
We will create a Python class Datethat supports adding and subtracting days. We will use the datetime module to handle date arithmetic 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
)
(
"Initial date:"
,
date
)
date_plus_10
=
date +
10
(
"Date after adding 10 days:"
,
date_plus_10
)
date_minus_5
=
date -
5
(
"Date after subtracting 5 days:"
,
date_minus_5
)
Code analysis:
__init__method: initializes theDateclass, taking year, month and day as parameters and converting them into adatetimeobject.__add__method: overloads the addition operator+, allowing a date object to be added to a number of days and returning a newDateobject.__sub__method: overloads the subtraction operator-, allowing days to be subtracted from a date object and returning a newDateobject.__str__method: overrides the string representation and returns a formatted date string.
Output result:
初始日期: 2023-10-01
加 10 天后的日期: 2023-10-11
减 5 天后的日期: 2023-09-26
Python3 Examples