Home > python > subtract a day from a python date

subtract a day from a python date

When working with dates, I prefer the order yyyy-mm-dd (e.g. 2015-07-10). Its main advantage is that if you use it as a prefix and sort your entries, you get them in chronological order. (Another advantage is that in my home country we use this order, so this is much closer to my thinking).

So, I faced the following problem: having a date as a string (“2015-07-10”), calculate the date one day before and produce a string again (“2015-07-09”).


>>> from datetime import datetime, timedelta
>>> date = "2015-07-10"
>>> today = datetime.strptime(date, '%Y-%m-%d')
>>> today
datetime.datetime(2015, 7, 10, 0, 0)
>>> yesterday = today - timedelta(days=1)
>>> yesterday
datetime.datetime(2015, 7, 9, 0, 0)
>>> yesterday.strftime('%Y-%m-%d')


Back to dates: if I need to write a date in English, I write it like this: “May 12, 1984”. Avoid “05-12-1984”, because what is it? May 12? Or December 5? God knows only.

Categories: python Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

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

%d bloggers like this: