简体   繁体   中英

How do I calculate the date Three months from a input date using python

I am using the datetime Python module. I am looking to calculate the date 3 months from the input date. Can you help me to get out of this issue.Thanks in advance

import datetime
today = "2022-02-24"

three = today + datetime.timedelta(30*3)
print (three)

Also I tried using "relativedelta"

You can't add a timedelta to a string, you need to add it to a datetime instance

Note that 90 days, isn't really 3 months

from datetime import datetime, timedelta

today = "2022-02-24"
three = datetime.strptime(today, "%Y-%m-%d") + timedelta(30 * 3)
print(three)  # 2022-05-25 00:00:00

three = datetime.today() + timedelta(30 * 3)
print(three)  # 2022-05-24 21:32:35.048700

With relativedelta of dateutil package, you can use:

from dateutil.relativedelta import relativedelta
from datetime import date

three = date.today() + relativedelta(months=3)

Output:

>>> three
datetime.date(2022, 5, 23)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM