使用 Unicode 格式来格式化 Python 的 `time.strftime()` 函数输出

19

我正在尝试使用Unicode格式字符串调用Python的time.strftime()函数:

u'%d\u200f/%m\u200f/%Y %H:%M:%S'

(\u200f是“从右到左标记”(RLM))

然而,我遇到了一个异常,即无法将RLM字符编码为ascii:

UnicodeEncodeError: 'ascii'编解码器无法在第2个位置编码字符u'\u200f':该序号不在128的范围内

我尝试寻找替代方案,但没有找到合理的替代方案。是否有此功能的替代方法或使其与Unicode字符一起使用的方法?

3个回答

28

许多标准库函数仍然没有正确支持Unicode。您可以使用以下解决方法:

import time
my_format = u'%d\u200f/%m\u200f/%Y %H:%M:%S'
my_time   = time.localtime()
time.strftime(my_format.encode('utf-8'), my_time).decode('utf-8')

1
请注意,Python 3 的行为将有所不同,请参阅我的错误报告(http://bugs.python.org/issue8304)。 - AndiDog
1
啊!这个信息被全球一半以上的人需要(只有 Python 用户),而且它就在这里找到了...太好了! - Dominique Guardiola
注意不要在此处使用硬编码的编码方式——strftime使用的编码方式可能取决于您的环境。 - fredrikhl

4
你可以通过UTF-8编码格式来格式化字符串:
time.strftime(u'%d\u200f/%m\u200f/%Y %H:%M:%S'.encode('utf-8'), t).decode('utf-8')

0

你应该以Unicode格式从文件中读取,然后将其转换为日期时间格式。

from datetime import datetime

f = open(LogFilePath, 'r', encoding='utf-8')
# Read first line of log file and remove '\n' from end of it
Log_DateTime = f.readline()[:-1]

您可以像这样定义日期时间格式:

fmt = "%Y-%m-%d %H:%M:%S.%f"

但是像C#这样的编程语言不容易支持它,所以您可以改为:

fmt = "%Y-%m-%d %H:%M:%S"

或者你可以使用以下方式(以满足.%f):
Log_DateTime = Log_DateTime + '.000000'

如果您遇到了无法识别的符号(Unicode 符号),那么您也应该将其删除。
# Removing an unrecognized symbol at the first of line (first character)
Log_DateTime = Log_DateTime[1:] + '.000000'

最后,您应该将字符串日期时间转换为实际的日期时间格式:
Log_DateTime = datetime.datetime.strptime(Log_DateTime, fmt)
Current_Datetime = datetime.datetime.now() # Default format is '%Y-%m-%d %H:%M:%S.%f'
# Calculate different between that two datetime and do suitable actions
Current_Log_Diff = (Current_Datetime - Log_DateTime).total_seconds()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接