strptim的奇怪编码问题

2024-10-03 11:16:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要改变主意

14 Şubat 2015 Cumartesi, 09:47:49

迄今为止。当我打印这个日期时,它工作得很好,但我无法更改time.strptime内部的编码,无论我尝试编码或解码为不同的类型。这是我的密码

# -*- coding: cp1254 -*-
import chardet
import time
from time import mktime
import datetime

h="14 Şubat 2015 Cumartesi, 09:47:49"

kc= datetime.datetime.fromtimestamp(mktime(time.strptime(h.decode('utf-8), "%d %B %Y %A,%H:%M:%S") ))
print kc

打印chardet.检测(h) 结果是

^{pr2}$

Tags: import密码类型编码datetimetime解码主意
3条回答

假设您正试图用土耳其日期的字符串表示创建一个datetime对象。在

您需要做的第一件事是将文件的源代码编码从cp1254更改为utf-8,这基本上涵盖了更广泛的字符集。在

# -*- coding: utf-8 -*-

其次,您应该将语言环境设置为tr_TR,以便Python在创建日期对象时理解Şubat的含义。在

^{pr2}$

然后,可以执行以下操作将日期字符串转换为实际的datetime.datetime对象。在

import datetime

str_date = '14 Şubat 2015 Cumartesi, 09:47:49'
date_obj = datetime.datetime.strptime(str_date, "%d %B %Y %A, %H:%M:%S")

print date_obj
# will print datetime.datetime(2015, 2, 14, 9, 47, 49)

希望这有帮助。在

h应为unicode字符串:

h=u"14 Şubat 2015 Cumartesi, 09:47:49"

我认为您需要将行改为:

^{pr2}$

(无法验证,因为我不知道区域设置,而且由于它我得到了错误)

确保您的区域设置为标识Şubat和{}

有:

import locale
locale.setlocale(locale.LC_ALL, <your locale>)

找到这个解决方案是件痛苦的事。这是一个Windows解决方案。从你的帖子里不清楚你在用什么操作系统。经验教训:

Python解决方案

下面是.lower()解决方案。我特别使用了utf-8的源代码来明确strptime使用的字符串必须是正确的cp1254编码。在

# coding: utf8
import locale
import datetime
locale.setlocale(locale.LC_ALL,'turkish')
print(locale.getlocale())

h = u"14 Şubat 2015 Cumartesi, 09:47:49"
kc = datetime.datetime.strptime(h.lower().encode('cp1254'), '%d %B %Y %A, %H:%M:%S')
print kc

输出:

^{pr2}$

Python 3.4.2解决方案

python3默认使用Unicode来处理所有事情,这使得事情变得更简单,Şubat的情况问题也得到了修复。在

# coding: utf8
import locale
import datetime
locale.setlocale(locale.LC_ALL,'turkish')
print(locale.getlocale())

h = '14 Şubat 2015 Cumartesi, 09:47:49'
kc = datetime.datetime.strptime(h, '%d %B %Y %A, %H:%M:%S')
print(kc)

输出:

^{pr2}$

相关问题 更多 >