Skip to content

Instantly share code, notes, and snippets.

@seanh
Created November 12, 2009 11:14
Show Gist options
  • Select an option

  • Save seanh/232823 to your computer and use it in GitHub Desktop.

Select an option

Save seanh/232823 to your computer and use it in GitHub Desktop.
Formatting dates and times as strings (Python)
"""
[date], [datetime] and [time] objects in Python have a [strftime] method for creating string representations in whatever format you want. (See the strftime link for the strftime syntax.)
[date]: http://docs.python.org/library/datetime.html#datetime.date
[datetime]: http://docs.python.org/library/datetime.html#datetime.datetime
[time]: http://docs.python.org/library/datetime.html#datetime.time
[strftime]: http://docs.python.org/library/datetime.html#strftime-behavior
"""
def format_date_numerical(date):
"""Take a date or datetime object and return a string of the form
YYYY_MM_DD."""
return date.strftime("%Y_%m_%d")
def format_date_pretty(date):
"""Take a date or datetime object and return a string of the form
Thursday 15 January 2009."""
return date.strftime("%A %d %B %Y")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment