[英]Using a Unicode format for Python's `time.strftime()`
我试图使用Unicode格式字符串调用Python的time.strftime()
函数:
u'%d\u200f/%m\u200f/%Y %H:%M:%S'
( \
是“从右到左标记”(RLM)。)
但是,我得到一个例外,即RLM字符无法编码为ascii:
UnicodeEncodeError:'ascii'编解码器无法对位置2中的字符u'\\ u200f'进行编码:序数不在范围内(128)
我试图寻找替代方案,但找不到合理的方法。 是否有替代此函数的方法,或使其与Unicode字符一起使用的方法?
许多标准库函数仍然不支持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')
您可以通过utf-8编码格式化字符串:
time.strftime(u'%d\u200f/%m\u200f/%Y %H:%M:%S'.encode('utf-8'), t).decode('utf-8')
您应该从文件中读取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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.