Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Create a Python Class Supporting Date Addition and Subtraction

Create a Python Class Supporting Date Addition and Subtraction

Document Object Reference Manual Python3 Examples

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

(

days

=

days

)

       

return

Date

(

new_date.

year

,

new_date.

month

,

new_date.

day

)

   

def

sub

(

self

,

days

)

:

        new_date

=

self

.

date

(

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 analysis:

  1. __init__ method: initializes the Date class, taking year, month and day as parameters and converting them into a datetime object.
  2. __add__ method: overloads the addition operator +, allowing a date object to be added to a number of days and returning a new Date object.
  3. __sub__ method: overloads the subtraction operator -, allowing days to be subtracted from a date object and returning a new Date object.
  4. __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

Document Object Reference Manual Python3 Examples