Python中可以使用datetime
模塊來實現日期的加減功能。具體步驟如下:
datetime
模塊from datetime import datetime, timedelta
date
date = datetime(year, month, day)
timedelta
來加減日期# 加一天
new_date = date + timedelta(days=1)
# 減一天
new_date = date - timedelta(days=1)
# 加一周
new_date = date + timedelta(weeks=1)
# 減一周
new_date = date - timedelta(weeks=1)
完整示例代碼如下:
from datetime import datetime, timedelta
date = datetime(2022, 1, 1)
new_date = date + timedelta(days=1)
print(new_date)
new_date = date - timedelta(days=1)
print(new_date)
new_date = date + timedelta(weeks=1)
print(new_date)
new_date = date - timedelta(weeks=1)
print(new_date)
這樣就可以實現對日期進行加減的功能了。