0 패딩없이 파이썬 DateTime 서식
-
15-11-2019 - |
문제
날짜와 시간에 0 패딩을 사용하지 않는 Python DateTimes를 인쇄하는 형식이 있습니까?
형식이 지금 사용하고 있습니다 :
mydatetime.strftime('%m/%d/%Y %I:%M%p')
.
결과 : 02/29/2012 05:03
원하는 : 2/29/2012 5:03 PM
어떤 형식이 '02'대신 '2'로서 '05 : 03pm '대신'5:03 pm '대신'5:03 pm '을 나타냅니다.
해결책
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", " ")
다른 팁
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.
The 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.
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.
Good answer from Chris Freeman on Linux.
On windows, it's:
mydate.strftime('%#m/%#d/%Y')
Thought that might help.