Python Recipe: Print a future date in the format you want.
Enough with all the talky talky, here’s a simple snippet I cooked up for a friend this morning to solve his problem of the moment: how to coax Python into printing out a future date (6 weeks in the future, to be exact) in the format he wants. Hope it’s useful to somebody. Let me know if I screwed anything up.
>>> import datetime >>> now = datetime.datetime.now() >>> print now 2008-04-21 10:19:35.832928 >>> from datetime import timedelta >>> diff = datetime.timedelta(days=42) >>> print diff 42 days, 0:00:00 >>> print now + diff 2008-06-02 10:19:35.832928 >>> future = now + diff >>> future.strftime("%m/%d/%Y") '06/02/2008' |
Documentation on how you can customize strftime to print dates in the format you need can be found here. Scroll down to the middle-ish part of the page.
Tagscode, computer-assisted reporting, date, datediff, datetime, format, formatting, print, python, python future date, recipe, snippet, strftime, timedelta














tommygun wrote:
thanks, dr. ben … i live for these things!
Posted on 28-Apr-08 at 11:16 am | Permalink
palewire wrote:
Have you ever worked through Dive Into Python or How To Think Like a Python Programmer? They’re filled with wonderful examples, and much more insightful explanation than I can provide.
Posted on 28-Apr-08 at 11:08 pm | Permalink