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.

Share this post

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • del.icio.us
  • Facebook
  • Mixx
  • NewsVine
  • Reddit
  • Slashdot
  • SphereIt
  • TwitThis
  • Fark
  • Technorati
  • Ma.gnolia
  • StumbleUpon
Tagscode, , , , , , , , , , , , ,

Related posts

Rate this post


1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Comments (2) left to “Python Recipe: Print a future date in the format you want.”

  1. tommygun wrote:

    thanks, dr. ben … i live for these things!

  2. 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.

Post a Comment

*Required
*Required (Never published)