简体   繁体   English

为Python的`time.strftime()`使用Unicode格式

[英]Using a Unicode format for Python's `time.strftime()`

I am trying to call Python's time.strftime() function using a Unicode format string: 我试图使用Unicode格式字符串调用Python的time.strftime()函数:

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

( \‏ is the "Right-To-Left Mark" (RLM).) \‏是“从右到左标记”(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'\‏' 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字符一起使用的方法?

Many standard library functions still don't support Unicode the way they should. 许多标准库函数仍然不支持Unicode。 You can use this workaround: 您可以使用此解决方法:

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')

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM