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?
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?
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')