Python Days and Weeks between Two Dates

During the normal course of business or life, you will often need to know the number of days or weeks between two dates. This is a simple thing to do within the same month, but for dates in different months or even different years this can be a tricky little task. Thankfully Python comes with “batteries included” to meet your date-computational needs. Here are some examples:

# NOTE: example using Python 3.x
import datetime
# Prior date example of "11 July 2013"
old_date = datetime.date(2013,7,11)
# New date example of "today"
new_date = datetime.date.today()
date_delta = new_date - old_date
# date_delta is a "datetime.timedelta" object
# "date_delta.days" gives an integer number of days
print("Days Between = %s" % date_delta.days)
print("Weeks Between = %s" % (date_delta.days/7.0))
# related example, add 30 days to date
print("30 days from %s is %s" % \
  ( new_date, new_date+datetime.timedelta(days=30) ))

Here are some related discussions for more:

Advertisements

About notesbytom

Keeping technology notes on WordPress.com to free up my mind to solve new problems rather than figuring out the same ones repeatedly :-).
This entry was posted in Python. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s