之前用代码:
@app.template_filter(‘date_format’) def _jinja2_filter_datetime_format(datetimeValue, format=u’%m月%d日’): """convert a date to a different format.""" gLog.debug("datetimeValue=%s, format=%s", datetimeValue, format) formatUtf8 = format.encode("UTF-8") formattedDate = datetime.strftime(datetimeValue, formatUtf8) formattedDateUnicode = formattedDate.decode(‘utf-8’) gLog.debug("type(formattedDate)=%s, formattedDateUnicode=%s", type(formattedDate), formattedDateUnicode) return formattedDateUnicode |
结果格式化出来的,月和日,即使小于10的话,也是前面补0的2位数
09/08
此处希望:
月和日,当小于10,去掉补的0,显示:
9/8
python datetime format single digit
Python strptime – Handling single digit dates – Stack Overflow
Formatting date/time (w/o adding the "0") | Codecademy
-》看来只能自己手动去格式化了?
datetime – python convert single digit day and month to two digits – Stack Overflow
8.1. datetime — Basic date and time types — Python 2.7.12 documentation
“%d Day of the month as a zero-padded decimal number. 01, 02, …, 31
%m Month as a zero-padded decimal number. 01, 02, …, 12”
python day of month not zero padded
Python datetime formatting without zero-padding – Stack Overflow
-》前面加上负号就可以了?
去试试
%-m/%-d
用代码:
@app.template_filter(‘datetime_format’) #def _jinja2_filter_datetime_format(datetimeValue, format=u’%m/%d %H:%M’): # def _jinja2_filter_datetime_format(datetimeValue, format=u’%m月%d日 %H:%M’): def _jinja2_filter_datetime_format(datetimeValue, format=u’%-m/%-d %H:%M’): """convert a datetime to a different format.""" gLog.debug("datetimeValue=%s, format=%s", datetimeValue, format) formatUtf8 = format.encode("UTF-8") formattedDatetime = datetimeValue.strftime(formatUtf8) formattedDatetimeUnicode = formattedDatetime.decode(‘UTF-8’) gLog.debug("formattedDatetimeUnicode=%s", formattedDatetimeUnicode) return formattedDatetimeUnicode |
然后月和日就可以正常显示,不加前缀的0了:
[总结]
此处,对于Python中的datetime,去格式化的时候,月和日,默认是all zero padding,(当小于10的时候)会自动加上前缀0的:
即:
%m/%d |
输出:
09/08
想要输出:
9/8
则可以在字母前加上减号:
%-m/%-d |
即可。
[后记]
padding – Python strftime – date without leading 0? – Stack Overflow
-》
前面加上减号,可以去掉补充的0,的这个功能:
仅适用于Unix/Linux,Windows(Cygwin)不支持