Python strftime - date without leading 0?

PythonPaddingStrftime

Python Problem Overview


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!

Python Solutions


Solution 1 - Python

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.

This only works on Unix (Linux, OS X), not Windows (including Cygwin). On Windows, you would use #, e.g. %Y/%#m/%#d.

Solution 2 - Python

We can do this sort of thing with the advent of the format method since python2.6:

>>> import datetime
>>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = datetime.datetime.now())
'2013/4/19'

Though perhaps beyond the scope of the original question, for more interesting formats, you can do stuff like:

>>> '{dt:%A} {dt:%B} {dt.day}, {dt.year}'.format(dt=datetime.datetime.now())
'Wednesday December 3, 2014'

And as of python3.6, this can be expressed as an inline formatted string:

Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dt = datetime.datetime.now()
>>> f'{dt:%A} {dt:%B} {dt.day}, {dt.year}'
'Monday August 29, 2016'

Solution 3 - Python

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'

Solution 4 - Python

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.

Solution 5 - Python

>>> import datetime
>>> d = datetime.datetime.now()
>>> d.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','')
'5/5/2011'

Solution 6 - Python

On Windows, add a '#', as in '%#m/%#d/%Y %#I:%M:%S %p'

For reference: https://msdn.microsoft.com/en-us/library/fe06s4ak.aspx

Solution 7 - Python

quite late to the party but %-d works on my end.

datetime.now().strftime('%B %-d, %Y') produces something like "November 5, 2014"

cheers :)

Solution 8 - Python

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')    

Solution 9 - Python

Take a look at - bellow:

>>> from datetime import datetime
>>> datetime.now().strftime('%d-%b-%Y')
>>> '08-Oct-2011'
>>> datetime.now().strftime('%-d-%b-%Y')
>>> '8-Oct-2011'
>>> today = datetime.date.today()
>>> today.strftime('%d-%b-%Y')
>>> print(today)

Solution 10 - Python

simply use replace like this:

(datetime.date.now()).strftime("%Y/%m/%d").replace("/0", "/")

it will output:

'2017/7/21'

Solution 11 - Python

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().

Solution 12 - Python

using, for example, "%-d" is not portable even between different versions of the same OS. A better solution would be to extract the date components individually, and choose between date specific formatting operators and date attribute access for each component.

e = datetime.date(2014, 1, 6)
"{date:%A} {date.day} {date:%B}{date.year}".format(date=e)

Solution 13 - Python

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.

Solution 14 - Python

Based on Alex's method, this will work for both the start-of-string and after-spaces cases:

re.sub('^0|(?<= )0', '', "01 January 2000 08:00am")

I like this better than .format or %-d because this is cross-platform and allows me to keep using strftime (to get things like "November" and "Monday").

Solution 15 - Python

Old question, but %l (lower-case L) worked for me in strftime: this may not work for everyone, though, as it's not listed in the Python documentation I found

Solution 16 - Python

import datetime
now = datetime.datetime.now()
print now.strftime("%b %_d")

Solution 17 - Python

if we want to fetch only date without leading zero we can

d = date.today()
day = int(d.strftime("%d"))

Solution 18 - Python

Python 3.6+:

from datetime import date
today = date.today()
text = "Today it is " + today.strftime(f"%A %B {today.day}, %Y")

Solution 19 - Python

I am late, but a simple list slicing will do the work

today_date = date.today().strftime('%d %b %Y')
if today_date[0] == '0':
    today_date = today_date[1:]

Solution 20 - Python

The standard library is good enough for most cases but for a really detailed manipulation with dates you should always look for some specialized third-party library.

Using Arrow:

>>> import arrow
>>> arrow.utcnow().format('dddd, D. M. YYYY')
'Friday, 6. 5. 2022'

Look at the full list of supported tokens.

Solution 21 - Python

Use simply strftime("%Y/%-m/%-d") in place of strftime("%Y/%m/%d") to remove zero :

strftime("%Y/%-m/%-d") ==> 2022/5/3 strftime("%Y/%-m/%-d") =>2022/05/03

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSolihullView Question on Stackoverflow
Solution 1 - PythonRyanView Answer on Stackoverflow
Solution 2 - PythonmgilsonView Answer on Stackoverflow
Solution 3 - PythonAlex MartelliView Answer on Stackoverflow
Solution 4 - PythonnewacctView Answer on Stackoverflow
Solution 5 - Pythongdw2View Answer on Stackoverflow
Solution 6 - PythonChad KennedyView Answer on Stackoverflow
Solution 7 - Pythonbonbon.langesView Answer on Stackoverflow
Solution 8 - PythonmcqwertyView Answer on Stackoverflow
Solution 9 - PythonptronicoView Answer on Stackoverflow
Solution 10 - PythonMohammad Hossein ShojaeiniaView Answer on Stackoverflow
Solution 11 - PythonNathan ViboonchanView Answer on Stackoverflow
Solution 12 - PythonChris ChewaView Answer on Stackoverflow
Solution 13 - PythonBrandon RhodesView Answer on Stackoverflow
Solution 14 - PythonmmitchellView Answer on Stackoverflow
Solution 15 - PythonOliverRadiniView Answer on Stackoverflow
Solution 16 - Pythonuser7503128View Answer on Stackoverflow
Solution 17 - PythonAliAxgharView Answer on Stackoverflow
Solution 18 - PythonItMView Answer on Stackoverflow
Solution 19 - PythonzerocoolView Answer on Stackoverflow
Solution 20 - PythonJeyekomonView Answer on Stackoverflow
Solution 21 - PythonChandra BhanView Answer on Stackoverflow