最新消息:20210917 已从crifan.com换到crifan.org

[已解决]Python中格式化日期时间后月日中不带额外的0只有1位的数字

Python crifan 7953浏览 0评论

之前用代码:

@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)不支持

转载请注明:在路上 » [已解决]Python中格式化日期时间后月日中不带额外的0只有1位的数字

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
92 queries in 0.181 seconds, using 23.35MB memory