Python strftime - date without leading 0?
Asked Answered
F

22

427

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!

Fears answered 25/5, 2009 at 0:11 Comment(0)
G
818

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:

>>> import datetime
>>> datetime.datetime(2023, 1, 2).strftime("%Y/%-m/%-d")
'2023/1/2'

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

Goosefish answered 15/1, 2010 at 16:38 Comment(19)
Doesn't even work for me, gives a ValueError (windows, python 2.6)Yttriferous
Works for me, linux python2.6! +1s for Ryan and Cory!Snorkel
It worked for me on OS X, but I'm using the Python 2.7.2 from python.org.Gunnery
Worked for me, both on OSX and Linux (debian)Riane
Works in OS X 10.8.5 with Python 2.7.2, but not in Windows 7 Pro 64-bit with Python 2.7.3.Earthly
Thanks for this great tips.. Worked like charm for Ubuntu 12.4 django-1.5Lexie
@moose I asked a question about this :-) here is the answer -> #28894672Murdock
I get ValueError: '-' is a bad directive in format '%b %-d, %Y'. OSX, Python 2.7.Songer
%#d would do the same on WindowsDeclension
I get ValueError, using Linux jupyter notebookCannery
Doesn't work on alpine, which is linux, be careful since it will generate an empty string without any expectation!Seychelles
Didn't know about # on Windows!Pillow
The # does not work on Win 10.0.17134 N/A version 17134 + python 3.6.0 ValueError: '#' is a bad directive in format '%a. %#d %B %Y, %H:%M'Renayrenckens
Works with Ruby too.Jagir
@Renayrenckens I encountered the same error in Windows 10 with Python 3.8.1 (ValueError: '#' is a bad directive in format). This error occurred when using strptime (%#d not OK) but not when using strftime (%d OK). In strptime, using %d without # seemed to work fine though even for parsing dates without leading zeroes.Imperturbation
Now that I knew what I am looking for, I found this explained in the strftime man page. It is a Glibc extension.Tamtama
This works with embedded Ruby, too. Thank you!Schulte
Didn't work for me in Win10, giving error as: ValueError: '#' is a bad directive in format '%Y-%#m-%#d %H:%M'Higinbotham
Hyphen trick only works on Linux. Hash trick only works on Windows. See this answerCowlick
A
215

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'
Asphaltite answered 19/4, 2013 at 4:48 Comment(5)
Very nice! Unfortunately doesn't work alone if you want to use textual representation like time.strftime('%A %B %d, %Y'), which yields (now, on English locale) Tuesday October 07, 2014.Postage
@PekkaKlärck -- Some reason I hadn't noticed your comment until now. It turns out that datetime specifies a very interesting __format__ hook that allows you to write things like that.Asphaltite
One problem is that '{dt.hour}' uses a 24 hour clock :(. Using the second option still brings you back to using '{%#I}' on Windows and '{%-I}' on Unix.Garlan
Good point. I never use 12 hour clock representations in code, so I didn't think of that case.Asphaltite
I'd suggest looking at this additional documentation on the format functionality: pyformat.infoParies
Q
47

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'
Querist answered 25/5, 2009 at 0:22 Comment(2)
@guneysus what do you mean? It should result in '1 January 2000'Prevaricator
@Prevaricator The above code checks for a blank space before 0 which in case of "01 January 2000" is not present.Gusher
T
41

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

Compare with the Python documentation of strftime() Format Codes. %d is documented:

%d: Day of the month as a zero-padded decimal number. Examples: 01, 02, …, 31

But %e is not documented. Even though it is not documented, it does seem to work for me regardless (running Linux):

>>> import datetime
>>> datetime.datetime(2023, 1, 1).strftime("%e")
' 1'

I don't know if it will work on your operating system.

Tenner answered 25/5, 2009 at 18:13 Comment(7)
%e fails for me on Windows w/ Python 2.6. I'm guessing it's *nix specific. Too bad :(Yttriferous
This is the cleanest, most general, solution---on a *nix system, at least. This works on OS X.Eohippus
Like the %-d above, this works in OS X 10.8.5 with Python 2.7.2, but not in Windows 7 Pro 64-bit with Python 2.7.3.Earthly
This worked for me on Windows 7 SP1 with Python 3.5.1.Selfseeker
This introduced an extra space instead of the leading zero so if you are looking for an exact match this may not be it. >>> one = datetime.datetime(2019, 5, 1, 23, 28, 48, 175214) >>> one.strftime('%b %e %H') 'May 1 23' >>> eleven = datetime.datetime(2019, 5, 11, 23, 28, 48, 175214) >>> eleven.strftime('%b %e %H') 'May 11 23'Ileneileo
Works with modern pandas/pythonScarbrough
Works! Combine %e with a .replace(' ','') for a solution.Ardolino
S
38
>>> import datetime
>>> d = datetime.datetime.now()
>>> d.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','')
'5/5/2011'
Sterlingsterlitamak answered 5/5, 2011 at 15:46 Comment(4)
This works 01 January 2000,Alexs is not works.Retinol
What's the point of doing .replace('X0','X').replace('X','')? Just do .replace('X0', '') and it'll be good.Thymus
@MarcoBonelli: Try your suggestion on the string "X12/X12/14" and you will see.Sterlingsterlitamak
This is hack, but it's a pythonic hack.Homoio
A
26

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

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

Amazing answered 31/7, 2015 at 14:12 Comment(0)
L
25

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

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

cheers :)

Laconia answered 25/11, 2014 at 11:8 Comment(4)
duplicate of the leading answer? https://mcmap.net/q/80802/-python-strftime-date-without-leading-0Sterlingsterlitamak
ValueError: Invalid format string in my Windows system.Pashto
As stated in the leading answer, using - "only works on Unix (Linux, OS X), not Windows (including Cygwin). On Windows, you would use #"Warmth
Agreed, does not work on my windows but ok in Linux. Craziness!Grand
C
11

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)
Craal answered 8/10, 2011 at 18:15 Comment(3)
Works perfectly in python 3Anabas
This should be the accepted answer. Does what is asked, super simple and easy to remember. Browsing quickly through the docs I was not able to find this information.Freddyfredek
"This should be the accepted answer". No it should not, as this only works on Linux.Wordbook
B
10

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')    
Breakaway answered 15/9, 2009 at 16:31 Comment(1)
Note that if you're like me and you're not building your app in django, you'll need to tell django you don't need to configure it: import django.conf django.conf.settings.configure()Prowler
D
8

simply use replace like this:

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

it will output:

'2017/7/21'
Diplocardiac answered 21/7, 2017 at 16:51 Comment(1)
This unfortunately does not work for dates formatted like 1.4.2021 (1st of April 2021); it could catch the zero in months, but not for the days (using "01.04.2021".replace(".0",".") leads only to 01.4.2021)Preuss
L
4

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

Lenwood answered 19/7, 2010 at 23:33 Comment(2)
OP question was for a solution using a format specifier in a call to strftime, rather than a roll-your-own solution involving str()Patella
great answer, don't listen to dave hooperCanker
W
4

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)
Wyatt answered 18/4, 2018 at 0:52 Comment(1)
This is the perfect answer, it will work on Windows as well as Linux.Juju
L
4

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

d = date.today()
day = int(d.strftime("%d"))
Lombardo answered 2/1, 2022 at 17:4 Comment(1)
I find this solution interesting because it works with Windows and Linux.Downwards
I
2

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.

Inheritrix answered 25/5, 2009 at 0:23 Comment(0)
H
2

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

Hocker answered 17/11, 2014 at 18:19 Comment(0)
M
2

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

Murtagh answered 29/7, 2016 at 15:29 Comment(2)
I am using a Python-based package (weather station software called WeeWX) that only lets me specify percent-sign formatting, like this - not the complicated string-substitution stuff like most of the above answers use. The "%l" worked for me! (on Linux)Unrefined
@RobCranfill Very glad to hear this came in handy for someone! I remember it solved a rather annoying problem for me at the timeMurtagh
G
2
import datetime
now = datetime.datetime.now()
print now.strftime("%b %_d")
Glyceride answered 1/2, 2017 at 22:53 Comment(2)
This replaces the leading zero with a space, which is not what the OP asked forPatella
ValueError: '_' is a bad directive in format '%a %b %_d %H:%M:%S %Y' using python 3.5Cyclorama
L
1

Python 3.6+:

from datetime import date
today = date.today()
text = "Today it is " + today.strftime(f"%A %B {today.day}, %Y")
Licensee answered 3/12, 2020 at 5:36 Comment(0)
C
0

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:]
Chemoreceptor answered 7/12, 2020 at 4:53 Comment(0)
A
0

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.

Akilahakili answered 6/5, 2022 at 10:47 Comment(0)
M
0

A little bit tricky but works for me

ex. from 2021-02-01T00:00:00.000Z to 2021-02-1

from datetime import datetime

dateObj = datetime.strptime('2021-02-01T00:00:00.000Z','%Y-%m-%dT%H:%M:%S.%fZ')
dateObj.strftime('%Y-%m-{}').format(dateObj.day)

Mania answered 8/12, 2022 at 15:11 Comment(0)
M
0

An amateur approach to remove '0' prefix for Day & Month, by casting to 'int'

dt = "08/01/2023"
dtArr = d.split("/")
print(str(int(x[0]))+'/'+str(int(x[1]))+'/'+str(int(x[2])))
Muntin answered 23/8, 2023 at 23:34 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.