tags:

views:

1489

answers:

7

When using Python strftime, is there a way to remove the first 0 of the date if it's before the 10th ie. so 01 is 1? Can't find a %thingy for that?

Thanks!

+5  A: 

You can use left strip to remove the leading zero's

day = day.lstrip('0')

>>> day = '01'
>>> day.lstrip('0')
'1'
Nadia Alramli
Thank you! You are a genius!
Solihull
+5  A: 

Some platforms may support width and precision specification between % and the letter (such as 'd' for day of month), according to http://docs.python.org/library/time.html -- but it's definitely a non-portable solution (e.g. doesn't work on my Mac;-). Maybe you can use a string replace (or RE, for really nasty format) after the strftime to remedy that? e.g.:

>>> y
(2009, 5, 7, 17, 17, 17, 3, 127, 1)
>>> time.strftime('%Y %m %d', y)
'2009 05 07'
>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')
'2009 5 7'
Alex Martelli
A: 

Because Python really just calls the C language strftime(3) function on your platform, it might be that there are format characters you could use to control the leading zero; try "man strftime" and take a look. But, of course, the result will not be portable, as the Python manual will remind you. :-)

I would try using a new-style "datetime" object instead, which has attributes like "t.year" and "t.month" and "t.day", and put those through the normal, high-powered formatting of the "%" operator, which does support control of leading zeros. See http://docs.python.org/library/datetime.html for details. Better yet, use the "".format() operator if your Python has it and be even more modern; it has lots of format options for numbers as well. See: http://docs.python.org/library/string.html#string-formatting

Brandon Craig Rhodes
+2  A: 

Here is the documentation of the modifiers supported by strftime() in the GNU C library. (Like people said before, it might not be portable.) Of interest to you might be:

  • %e instead of %d will replace leading zero in day of month with a space

It works on my Python (on Linux). I don't know if it will work on yours.

newacct
+3  A: 

I find the Django template date formatting filter to be quick and easy. It strips out leading zeros. If you don't mind importing the Django module, check it out.

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date

from django.template.defaultfilters import date as django_date_filter
print django_date_filter(mydate, 'P, D M j, Y')
mcqwerty
A: 

Hi, actually I had the same problem, and I realized that if you add a hyphen between the '%' and the letter, you can remove the leading zero. For example '%Y/%-m/%-d'.

Ryan
works only in python 2.x
SilentGhost
A: 

for %d you can convert to integer using int() then it'll automatically remove leading '0' and becomes integer. You can then convert back to string using str()

Nathan Viboonchan