为 Python 的 `time.strftime()` 使用 Unicode 格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2571515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a Unicode format for Python's `time.strftime()`
提问by Hosam Aly
I am trying to call Python's time.strftime()
function using a Unicode format string:
我正在尝试time.strftime()
使用 Unicode 格式字符串调用 Python 的函数:
u'%d\u200f/%m\u200f/%Y %H:%M:%S'
(\u200f
is the "Right-To-Left Mark" (RLM).)
(\u200f
是“从右到左标记”(RLM)。)
However, I am getting an exception that the RLM character cannot be encoded into ascii:
但是,我收到一个异常,即 RLM 字符无法编码为 ascii:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u200f' in position 2: ordinal not in range(128)
UnicodeEncodeError: 'ascii' 编解码器无法对位置 2 中的字符 u'\u200f' 进行编码:序号不在范围内 (128)
I have tried searching for an alternative but could not find a reasonable one. Is there an alternative to this function, or a way to make it work with Unicode characters?
我曾尝试寻找替代方案,但找不到合理的方案。是否有此功能的替代方法,或使其与 Unicode 字符一起使用的方法?
回答by AndiDog
Many standard library functions still don't support Unicode the way they should. You can use this workaround:
许多标准库函数仍然不以应有的方式支持 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')
回答by Yaroslav
You can format string through utf-8 encoding:
您可以通过 utf-8 编码格式化字符串:
time.strftime(u'%d\u200f/%m\u200f/%Y %H:%M:%S'.encode('utf-8'), t).decode('utf-8')
回答by Saeed Zahedian Abroodi
You should read from a file as Unicode and then convert it to Date-time format.
您应该从文件中读取 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]
You can define Date-time format like this:
您可以像这样定义日期时间格式:
fmt = "%Y-%m-%d %H:%M:%S.%f"
But some programming language like C# doesn't support it easily, so you can change it to:
但是有些编程语言比如C#不容易支持,所以你可以改成:
fmt = "%Y-%m-%d %H:%M:%S"
Or you can use like following way (to satisfy .%f):
或者您可以使用如下方式(以满足 .%f):
Log_DateTime = Log_DateTime + '.000000'
If you have an unrecognized symbol (an Unicode symbol) then you should remove it too.
如果您有一个无法识别的符号(Unicode 符号),那么您也应该将其删除。
# Removing an unrecognized symbol at the first of line (first character)
Log_DateTime = Log_DateTime[1:] + '.000000'
At the end, you should convert string date-time to real Date-time format:
最后,您应该将字符串日期时间转换为真正的日期时间格式:
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()