最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]Python中需要把时间格式化为上午下午加上时间

Python crifan 8003浏览 0评论

已有对应的datetime中的time

需要格式化为:

下午 5:00

这种格式

能想到的是:

可以参考:

[已解决]Python中用strftime格式化datetime出错

去用:

%p %H:%M

然后把AM和PM,替换为上午和下午

但是不够智能

还是希望可以加上locale,自动输出上午和下午

python time format locale

Locale date formatting in Python – Stack Overflow

python – How do I strftime a date object in a different locale? – Stack Overflow

Python strftime reference

Formatting Python Dates According to Locale | skybert.net

结果还遇到了:

[已解决]Python中datetime的strftime中format中是unicode结果出错:UnicodeEncodeError: ascii codec can’t encode character  in position ordinal not in range

最后用代码:

@app.template_filter(‘time_format’)
def _jinja2_filter_datetime_format(datetimeValue, format=u’%p %H:%M’):
    “””convert a time to a different format.”””
    gLog.debug(“type(datetimeValue)=%s, datetimeValue=%s, format=%s”, type(datetimeValue), datetimeValue, format)
    formattedTime = datetimeValue.strftime(format)
    formattedTimeLower = formattedTime.lower()
    gLog.debug(“formattedTimeLower=%s”, formattedTimeLower)
    zhcnFormattedTimeLower = formattedTimeLower.replace(“am”, u”上午”)
    zhcnFormattedTimeLower = zhcnFormattedTimeLower.replace(“pm”, u”下午”)
    gLog.debug(“zhcnFormattedTimeLower=%s”, zhcnFormattedTimeLower) #下午 5:00
    return zhcnFormattedTimeLower

输出:

DEBUG in views [/root/html/SIPEvents/sipevents/views.py:446]:
type(datetimeValue)=<type ‘datetime.datetime’>, datetimeValue=2016-09-04 19:20:00, format=%p %H:%M

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in views [/root/html/SIPEvents/sipevents/views.py:449]:
formattedTimeLower=pm 19:20

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in views [/root/html/SIPEvents/sipevents/views.py:452]:
zhcnFormattedTimeLower=下午 19:20

<div–<——————————————————————————

暂时先凑合用吧。

转载请注明:在路上 » [已解决]Python中需要把时间格式化为上午下午加上时间

发表我的评论
取消评论

表情

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

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.168 seconds, using 22.16MB memory