Adding days to a date in Python using datetime and timedelta. Use Python Pandas to concatenate dates with strings.

I wanted to create 20 files with this syntax date-blog-post-name. I wrote a very extensive D3 Tutorial and wanted to break it down into smaller blog posts, published sequentially 5 days apart.

The blog posts needed to have this naming syntax:

YYYY-MM-DD-name-of-blog-post.md

I extracted the headlines H2 of the original blog post and made an array like this:

>>> posts = ['-setup-d3-step-by-step.md', '-d3-and-asynchronous.md', 
'-d3-and-incompatible-versions.md', '-d3-load-a-csv-file-with-promises.md', 
'-d3-convert-string-to-date.md', '-d3-bind-data-to-dom.md', '-d3-drawing-svg.md', 
'-d3-creating-a-bar-chart.md', '-d3-using-scales.md', '-d3-linear-scale.md', 
'-d3-band-scale.md', '-d3-scales-in-a-bar-chart.md', '-d3-responsive-visualization.md', '-d3-arrow-functions.md', '-d3-adding-axes-to-bar-chart.md', 
'-d3-bar-chart-title-and-labels.md', '-d3-visualization-margins.md', 
'-d3-mouse-event-handler.md', '-embedding-d3-in-a-website.md']

How do I add the prefix dates?

2020-05-12
2020-05-17
...

To have files like these?

2020-05-12-setup-d3-step-by-step.md
2020-05-17-d3-and-asynchronous.md
...

Adding days to a date in Python

Let’s get to it.

>>> import datetime
>>> datetime.date.today() + 5

Error:

TypeError: unsupported operand type(s) for +: 'datetime.date' and 'int'

Should I then add the days to the day in the date?

>>> datetime.date.today().day + 5
14

This can’t be right.

Adding days to date in Python with timedelta

Let’s look at the Python docs: datetime. Looking at timedelta

A timedelta object represents a duration, the difference between two dates or times.

You can do this:

new_date = old_date + datetime.timedelta(days=N)

With an example: