Python UnicodeEncodeError: 'locale' codec can't encode character ':' in time.strftime()
This error is caused by an encoding problem when formatting time using the strftime() function in Python. The issue arises when an un-encodable character is encountered. In this specific case, the character ':' (Unicode character \uFF1A) is causing the error because its Unicode encoding doesn't match the local encoding.
To resolve this, you can try changing the local encoding or using a format string that avoids characters incompatible with the encoding. Here are some suggestions:
-
Change Local Encoding: Set the local encoding to UTF-8, which supports a wide range of characters, by using
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')before usingstrftime(). -
Use Alternative Format String: Replace the colon (':') with a different character that's compatible with the local encoding. For example, you can use
current_time = time.strftime('%Y-%m-%d %H:%M', time.localtime())using a regular colon (':').
By implementing one of these solutions, the error should be resolved, and the strftime() function will successfully format the time.
原文地址: https://www.cveoy.top/t/topic/m02p 著作权归作者所有。请勿转载和采集!