简体   繁体   中英

Python subtract dates or days from date to get years, months, days

I am trying to subtract two dates or days from today's date. I want to get the result in years, months, days. How to do that?

Expecting 1 year, 2 months, 5 days , 20 days , 3 months, 2 days ago, etc. instead of just days.

import datetime
import pytz
tz='US/Pacific'
birthday = datetime.datetime(2020, 2, 19, 12, 0, 0)

>>> import datetime
>>> import pytz
>>> tz='US/Pacific'
>>> birthday = datetime.datetime(2020, 2, 19, 12, 0, 0)
>>> diff = datetime.datetime.now() - birthday
>>>
>>> diff
datetime.timedelta(days=326, seconds=39130, microseconds=319509)
>>>
>>> birthday = datetime.datetime(2015, 2, 19, 12, 0, 0)
>>> diff = datetime.datetime.now() - birthday
>>> diff
datetime.timedelta(days=2152, seconds=39151, microseconds=823846)
>>>
>>> diff.days
2152

Use dateutil.relativedelta from the dateutil package:

import datetime
from dateutil.relativedelta import relativedelta

>>> relativedelta(datetime.datetime.now(), datetime.datetime(2020, 2, 19, 12, 0, 0))
relativedelta(months=+10, days=+23, hours=+4, minutes=+8, seconds=+42, microseconds=+204978)

>>> relativedelta(datetime.datetime.now(), datetime.datetime(2015, 2, 19, 12, 0, 0))
relativedelta(years=+5, months=+10, days=+23, hours=+4, minutes=+9, seconds=+10, microseconds=+624971)

You can extract years, months, etc. like relativedelta().years , relativedelta().months , etc.

This answer may be helped you. But also you can check this using timetuple()

from datetime import datetime
import datetime
import pytz
tz = 'US/Pacific'
birthday = datetime.datetime(2020, 2, 19, 12, 0, 0)


b = birthday.timetuple()
n = datetime.datetime.now().timetuple()
print(f'Year diff: {n.tm_year-b.tm_year}')
print(f'Month diff: {n.tm_mon-b.tm_mon}')
print(f'Day diff: {n.tm_mday-b.tm_mday}')

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