Python date string formatting

I want to remove filled zeros from python date with string formatting:

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 replacement does not work - I get 01/1/2013. How to combine zero only if it is near the beginning of the line?

+4
source share
1 answer

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

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

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

and no need to replace zeros.

Demo:

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

If Python was compiled using the glibc library, you can also use dashes in the format to suppress padding:

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

but it is not so portable.

+11
source

Source: https://habr.com/ru/post/1501522/


All Articles