5

I want to remove the padded zeroes from a string-formatted python date:

formatted_date = my_date.strftime("%m/%d/%Y") # outputs something like: 01/01/2013
date_out = formatted_date.replace(r'/0', r'/').replace(r'^0', r'') 

The second replace doesnt work-- I get 01/1/2013. How do I match the zero only if it's next to the beginning of the string?

1 Answer 1

13

.replace() does not take regular expressions. You are trying to replace the literal text ^0.

Use str.format() to create a date format without zero-padding instead:

'{0.month}/{0.day}/{0.year}'.format(my_date)

and avoid having to replace the zeros.

Demo:

>>> import datetime
>>> today = datetime.date.today()
>>> '{0.month}/{0.day}/{0.year}'.format(today)
'9/10/2013'

If Python was compiled with the glibc library, then you could also use dashes in the format to suppress the padding:

my_date.strftime('%-m/%-d/%y')

but that is not nearly as portable.

Sign up to request clarification or add additional context in comments.

7 Comments

+1. It would be nice though if .strftime() had versions of the format strings that allowed the omission of leading zeros. Looks like this was considered and rejected.
@StevenRumbalski: That'd be up to the C-API strftime() call. The standard doesn't have any such format parameter, C99 did add %e (Day of the month, space-padded ( 1-31)) but no equivalent for the month, and none without any padding.
@StevenRumbalski: Ah, thanks for that link, that gave me a new trick (limited to glibc platforms).
I didn't know the indices within the string could access object properties. Upvote for answering the question AND giving me a new tool for later.
@NathanTregillus: use different formats? Better yet, use a localisation library like Babel to handle date formatting for you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.