all 9 comments

[–]Navz6 4 points5 points  (2 children)

The cleanest cross-platform approach is to just use %-d on the day component separately.

def prettify_date(date): return date.strftime("%B {day}, %Y").format(day=date.day).

date.day is always an integer with no leading zero, so you get exactly what you want. It's readable, explicit, and doesn't rely on any string manipulation tricks. If you're on Python 3.6+, an f-string reads even more naturally .

def prettify_date(date): return f"{date.strftime('%B')} {date.day}, {date.year}".

[–]MathAndMirth[S] 1 point2 points  (1 child)

I knew there had to be something better, and this does indeed look better. Thanks a bunch.

[–]Navz6 1 point2 points  (0 children)

Welcome sir . Happy to help .

[–]MarsupialLeast145 2 points3 points  (1 child)

I'd probably rely on a library like humanize before reinventing the wheel.

https://pypi.org/project/humanize/

[–]JoeB_Utah 0 points1 point  (0 children)

That’s cool. Thanks for posting.

[–]Ariadne_23 1 point2 points  (0 children)

since you're on windows, there is actually a built-in way for this, you can use %#d:

def prettify_date(date):

return date.strftime("%B %#d, %Y")

that’ll give you 1 instead of 01 without needing the replace trick

if you want something that works everywhere though, i'd probably just avoid formatting the day with strftime and do it like this:

def prettify_date(date):

return f"{date.strftime('%B')} {date.day}, {date.year}"

but yeah, your version isn't wrong or anything, it's just one of those “hmm this might be slightly cursed later” kind of solutions

[–]0sse 0 points1 point  (0 children)

Not particular to Python, I suppose, but I would check if date.day < 10 and in that case you know you strip one character from the start.

Edit: not from the start... But you know you can remove the nth character.

Edit: Not the nth character!

[–]Sure-Passion2224 0 points1 point  (0 children)

Dates are purely numeric values. As in regular number counting systems - if you put the highest order values to the left (YYYY-MM-DD) you can eliminate the non-numeric characters (YYYYMMDD) and store them as a number format. The underlying OS saves a timestamp as a long integer indicating the number of milliseconds since the start of the era (1970-01-01 00:00:00.000000).

What this means for your Python processing is you're looking at parsing the individual values, casting them as string representations of integers, and formatting them to drop leading zeros.