Tôi có thể xuất ra định dạng thời gian nhạy cảm miền địa phương bằng cách sử dụng strftime('%X')
, nhưng điều này luôn bao gồm giây. Làm thế nào tôi có thể hiển thị định dạng thời gian này mà không cần giây?Cách hiển thị định dạng thời gian nhạy cảm miền địa phương mà không cần giây trong python
>>> import locale
>>> import datetime
>>> locale.setlocale(locale.LC_ALL, 'en_IE.utf-8')
'en_IE.utf-8'
>>> print datetime.datetime.now().strftime('%X')
12:22:43
>>> locale.setlocale(locale.LC_ALL, 'zh_TW.utf-8')
'zh_TW.utf-8'
>>> print datetime.datetime.now().strftime('%X')
12時22分58秒
Cách duy nhất tôi có thể nghĩ để làm điều này đang nỗ lực để phân tích đầu ra của locale.nl_langinfo(locale.T_FMT)
và loại bỏ các bit giây, nhưng đó sẽ đem lại đó là thủ đoạn gian trá riêng.
>>> print locale.nl_langinfo(locale.T_FMT)
%H時%M分%S秒
>>> locale.setlocale(locale.LC_ALL, 'en_IE.utf-8')
'en_IE.utf-8'
>>> print locale.nl_langinfo(locale.T_FMT)
%T
Giải pháp: (. Dựa trên câu trả lời pixelbeat của)
# -*- coding: utf-8 -*-
import locale
def locale_time(t, show_seconds=False):
if show_seconds:
return t.strftime('%X')
replacement_fmts = [
(u'.%S', u''),
(u':%S', u''),
(u',%S', u''),
(u':%OS', ''),
(u'ཀསར་ཆ%S', u''),
(u' %S초', u''),
(u'%S秒', u''),
(u'%r', '%I:%M %p'),
(u'%t', '%H:%M'),
(u'%T', '%H:%M')
]
enc=locale.getpreferredencoding(do_setlocale=False)
t_fmt = locale.nl_langinfo(locale.T_FMT).decode(enc)
for fmt in replacement_fmts:
new_t_fmt = t_fmt.replace(*fmt)
if new_t_fmt != t_fmt:
return t.strftime(new_t_fmt.encode(enc))
return t.strftime(t_fmt.encode(enc)
Cách sử dụng:
>>> locale.setlocale(locale.LC_ALL, 'en_IE.utf-8')
'en_IE.utf-8'
>>> print locale_time(t)
15:47
>>> locale.setlocale(locale.LC_ALL, 'zh_TW.utf-8')
'zh_TW.utf-8'
>>> print locale_time(t)
15時47分
t_fmt = "% t" là một tab, do đó, rõ ràng là một lỗi. Tôi cho rằng nó phải là "% T" –