Formatting date strings in Python


/ Published in: Python
Save to your folder(s)

[date](http://docs.python.org/library/datetime.html#datetime.date), [datetime](http://docs.python.org/library/datetime.html#datetime.datetime) and [time](http://docs.python.org/library/datetime.html#datetime.time) objects in Python have a [strftime](http://docs.python.org/library/datetime.html#strftime-behavior) method for creating string representations in whatever format you want. (See the strftime link for the strftime syntax.)


Copy this code and paste it in your HTML
  1. def format_date_numerical(date):
  2. """Take a date or datetime object and return a string of the form
  3. YYYY_MM_DD."""
  4. return date.strftime("%Y_%m_%d")
  5.  
  6. def format_date_pretty(date):
  7. """Take a date or datetime object and return a string of the form
  8. Thursday 15 January 2009."""
  9. return date.strftime("%A %d %B %Y")

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.