简体   繁体   中英

How to get the next date which is a fraction year away from the given date?

I have a datetime object called dt and I want to get the next date which 0.93 years away from it. I was trying relativedelta but it seems that the function cannot take fractional years.

dt = datetime.datetime(2012, 4, 30)
dt + relativedelta(years = 0.93)

>> ValueError: Non-integer years and months are ambiguous and not currently supported.

Any help is appreciated.

relativedelta doesn't support fractions. Easiest way to do this would be to convert the fraction to seconds and use that. eg,

YEAR_SECONDS = 60 * 60 * 24 * 365
dt + relativedelta(seconds = int(0.93 * YEAR_SECONDS))

Try multiplying the float no by the number of days in a year. This will give you 0.93 * 365 days after the current date.

dt = datetime.datetime.today() + datetime.timedelta(days=int(365*.93))

OUTPUT:-

2020-05-09 08:40:28.507170

NOTE:-

In the above process we are converting into int, because the date is needed. If some more precise time duration (ie Hours, Minutes etc) is needed, then this process may not be the best.

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