Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

python - What is the difference between "datetime.timedelta" and "dateutil.relativedelta.relativedelta" when working only with days?

What is the difference between datetime.timedelta (from Python's standard library) and dateutil.relativedelta.relativedelta when working only with days?

As far as I understand, timedelta only supports days (and weeks), while relativedelta adds support for periods defined in terms of years, months, weeks or days, as well as defining absolute values for year, month or day. (remember, for the purposes of this question, I don't have to worry about hours, minutes or seconds)

Considering that I'm only working with datetime.date objects, and only interested in periods defined by the number of days, what's the difference between timedelta and relativedelta? Is there any difference?

from datetime import date, timedelta
from dateutil.relativedelta import relativedelta

i = -1  # This could have been any integer, positive or negative
someday = date.today()
# Is there any difference between these two lines?
otherday = someday + timedelta(days=i)
otherday = someday + relativedelta(days=i)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

dateutil is an extension package to the python standard datetime module. As you say, it provides extra functionality, such as timedeltas that are expressed in units larger than a day.

This is useful if you have to ask questions such as how many months can I save before my girlfriend's birthday comes up, or what's the last Friday in the month? This hides complex calculations that are caused by the different lengths of the months, or extra days in leap years.

In your case, you are only interested in the number of days. So you'd best use timedelta as this avoids an extra dependency on the dateutil package.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...