-1

I'm trying to convert/format dates in Python..

Currently it outputs:

2014-01-08

I'd like the output to be:

Monday, January 3rd

Having trouble understanding the documentation here, halp me format the date properly?

Marko Bajlovic
  • 323
  • 5
  • 12

1 Answers1

2

You can't quite do this in one go. If you look at the docs for strftime() and strptime() Behavior, there are format codes for the full weekday (%A) and month (%B), but there's nothing for the day of the month as an ordinal.

In general, whenever you want to do something strftime can't do, use as much of it as you can, and combine it with explicit code for the rest. Like this:

def ordinal(n):
    if 11 <= n <= 13:
        return '{}th'.format(n)
    if n%10 == 1:
        return '{}st'.format(n)
    elif n%10 == 2:
        return '{}nd'.format(n)
    elif n%10 == 3:
        return '{}rd'.format(n)
    else:
        return '{}th'.format(n)

Then, you can do this:

def my_format(dt):
    return '{} {}'.format(dt.strftime('%A, %B'), ordinal(dt.day))

I'm assuming that you're starting off with a date or datetime object. If not, you have to parse it first, of course. But that's easy:

datestring = '2014-01-08'
dt = datetime.datetime.strptime(datestring, '%Y-%m-%d')
abarnert
  • 354,177
  • 51
  • 601
  • 671
  • 1
    Maybe something like: `'{0:%A}, {0:%B} {1}'.format(dt, ordinal(dt.day))` and get rid of strftime call – Jon Clements Jan 09 '14 at 22:12
  • @JonClements: That's shorter, but for a novice I'm not sure I want to explain that `str.format` calls `d.strftime` on `datetime` objects. The more explicit way gives you a much more obvious error if you accidentally call it on a string. – abarnert Jan 09 '14 at 22:15
  • 1
    @JonClements: that can be shortened to `'{:%A, %B} {}'.format(dt, ordinal(dt.day))`; the full `strftime` format syntax can be used. – Martijn Pieters Jan 09 '14 at 22:20
  • Is there a more obvious demonstration of this ability of `.format` besides a small example in [this section of the docs](http://docs.python.org/2/library/string.html#format-examples)? I had no idea `.format` could call `strftime` on a `datatime` object, and I'm not surprised because it seems that it is only mentioned as an aside, and not explicitly. – SethMMorton Jan 09 '14 at 22:41
  • @SethMMorton: Yes. [`datetime.datetime.__format__`](http://docs.python.org/3.3/library/datetime.html#datetime.datetime.__format__) is fully documented. If you already know that `format` and `str.format` call the `__format__` dunder-method hook, it's pretty easy to find out what the capabilities are for any builtin/stdlib classes, because they're all documented. If you didn't already know that (because, say, you didn't read the [PEP](http://www.python.org/dev/peps/pep-3101/) or the python-ideas discussion 7 years ago), it's a bit less discoverable. – abarnert Jan 09 '14 at 23:28
  • @SethMMorton: In particular, [`format`](http://docs.python.org/3.3/library/functions.html#format) says "A call to `format(value, format_spec)` is translated to `type(value).__format__(format_spec)`, but [`str.format`](http://docs.python.org/3.3/library/stdtypes.html#str.format) doesn't, and many people don't know to look at the builtin for more info on the method. (Also, if you're using Python 2.x, many of the docs improvements weren't back-ported.) – abarnert Jan 09 '14 at 23:30
  • @abarnert Ah, and I am using python 2.x, so that's probably my issue. And I definitely was't programming 7 years ago so I didn't read those discussions :) Thanks for the explanation and the links. – SethMMorton Jan 09 '14 at 23:51