Is there a format for printing Python datetimes that won't use zero-padding on dates and times?
Format I'm using now:
mydatetime.strftime('%m/%d/%Y %I:%M%p')
Result: 02/29/2012 05:03PM
Desired: 2/29/2012 5:03PM
What format would represent the month as '2' instead of '02', and time as '5:03PM' instead of '05:03PM'
-
1Does this answer your question? Python strftime - date without leading 0?SuperStormer– SuperStormer2022年10月12日 02:40:27 +00:00Commented Oct 12, 2022 at 2:40
12 Answers 12
The other alternate to avoid the "all or none" leading zero aspect above is to place a minus in front of the field type:
mydatetime.strftime('%-m/%d/%Y %-I:%M%p')
Then this: '4/10/2015 03:00AM'
Becomes: '4/10/2015 3:00AM'
You can optionally place a minus in front of the day if desired.
Edit: The minus feature derives from the GNU C library ("glibc") as mentioned in the Linux strftime manpage under "Glibc notes"
4 Comments
date.__format__ or time.strftime, docs.python.org/3/library/…, and docs.python.org/3.8/library/time.html#time.strftime respectivelyThe new string formatting system provides an alternative to strftime. It's quite readable -- indeed, it might be preferable to strftime on that account. Not to mention the fact that it doesn't zero-pad:
>>> '{d.month}/{d.day}/{d.year}'.format(d=datetime.datetime.now())
'3/1/2012'
Since you probably want zero padding in the minute field, you could do this:
>>> '{d.month}/{d.day}/{d.year} {d.hour}:{d.minute:02}'.format(d=now)
'3/1/2012 20:00'
If you want "regular" time instead of "military" time, you can still use the standard strftime specifiers as well. Conveniently, for our purposes, strftime does provide a code for the 12-hour time padded with a blank instead of a leading zero:
'{d.month}/{d.day}/{d.year} {d:%l}:{d.minute:02}{d:%p}'.format(d=now)
'4/4/2014 6:00PM'
This becomes somewhat less readable, alas. And as @mlissner points out, strftime will fail on some (all?) platforms for dates before 1900.
8 Comments
"{0.day} {0:%B %Y}".format(d) which would give you '2 August 2013' as the day of this comment :)The formatting options available with datetime.strftime() will all zero-pad. You could of course roll you own formatting function, but the easiest solution in this case might be to post-process the result of datetime.strftime():
s = mydatetime.strftime('%m/%d/%Y %I:%M%p').lstrip("0").replace(" 0", " ")
9 Comments
.lstrip("0") to get rid of the leading zero.Accepted answer not a proper solution (IMHO) The proper documented methods:
In Linux "#" is replaced by "-":
%-d, %-H, %-I, %-j, %-m, %-M, %-S, %-U, %-w, %-W, %-y, %-Y
In Windows "-" is replaced by "#":
%#d, %#H, %#I, %#j, %#m, %#M, %#S, %#U, %#w, %#W, %#y, %#Y
#Linux
mydatetime.strftime('%-m/%d/%Y %-I:%M%p')
# Windows
mydatetime.strftime('%#m/%d/%Y %#I:%M%p')
Source: https://msdn.microsoft.com/en-us/library/fe06s4ak.aspx
As stated by Sagneta: The # hash trick on Windows is only available to native python executable. this will not work for cygwin-based python implementations.
3 Comments
Comments
another option:
yourdatetime.strftime('%-m/%-d/%Y %-I:%M%p')
Comments
As mentioned by several others, to ignore leading zero on windows, you must use %#d instead of %-d.
For those who like to write clean cross platform python code, without seeing platform switches in business logic, here is a Python3 helper that enables you to have one format string for both Windows, Linux and Others (tested Linux, Windows and FreeBSD):
import os
from datetime import datetime
def dateToStr(d: datetime, fmt: str) -> str:
return d.strftime(fmt.replace('%-', '%#') if os.name == 'nt' else fmt)
dateToStr(datetime.now(), '%-m/%-d/%-Y')
On a side note, this is another one of those Whaaaaaaaat? features in Python. I don't understand why they did not create a standard format set for all platforms and add an optional 'use_native' flag to use native platform features. Guess it was an early design decision that must be kept for legacy support.
1 Comment
"%l" (that's a lower-case L) works for the hour (instead of "%I"). I only know this from another answer here
Python strftime - date without leading 0?
but unfortunately they don't have the code for the other elements of a date/time.
1 Comment
I use this:
D = str(datetime.now().day)
MM = str(datetime.now().month)
YYYY = str(datetime.now().year)
This, today, will return: 2, 12, 2021
1 Comment
In the official docs formating section:
- When used with the strptime() method, the leading zero is optional for formats %d, %m, %H, %I, %M, %S, %J, %U, %W, and %V. Format %y does require a leading zero.
So, using %d to parse day in number will automatically parse both 07 & 7 for example.
1 Comment
I just came across this for the first time, since I previously did most development work on linux exclusively. Here is my solution for an easy cross-platform approach on Python 3.8+
from typing import AnyStr
import os
def unistrfmt(fmt: AnyStr) -> AnyStr:
return fmt.replace(('%#', '%-')[os.name == 'nt'], ('%-', '%#')[os.name == 'nt'])
# Examples:
from datetime import date
date.today().strftime(unistrfmt("%Y.%m.%-d"))
# '2024.02.1'
os.name
#'nt'
unistrfmt("%Y.%m.%-d")
# '%Y.%m.%#d'
unistrfmt("%Y.%m.%#d")
# '%Y.%m.%#d'
Comments
Add a # in front of the format descriptor to remove zero padding:
mydatetime.strftime('%#m/%d/%Y %#I:%M%p')
1 Comment
Explore related questions
See similar questions with these tags.