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?
Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.
A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With