PyQt5和datetime.datetime.strptime之间的冲突

时间:2016-09-23 10:37:56

标签: python datetime pyqt5

所以我正在编写一个工具,使用基于python 3.52和Qt5的图形用户界面从文件中读取时间。最小的操作

datetime.datetime.strptime('Tue', '%a')

在隔离环境中工作,输出“1900-01-01 00:00:00”。但是,当我运行以下最小例子时

import sys
import datetime as datetime

from PyQt5 import QtWidgets

if __name__ == '__main__' :
    print(datetime.datetime.strptime('Tue', '%a'))
    app = QtWidgets.QApplication(sys.argv)
    print(datetime.datetime.strptime('Tue', '%a'))
    #sys.exit(app.exec_())

我得到了输出

1900-01-01 00:00:00
Traceback (most recent call last):
File "/home/user/gui/testfile.py", line 11, in <module>
print(datetime.datetime.strptime('Tue', '%a'))
File "/usr/lib/python3.5/_strptime.py", line 510, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib/python3.5/_strptime.py", line 343, in _strptime
(data_string, format))
ValueError: time data 'Tue' does not match format '%a'

因此,对 strptime 例程的第一次调用工作正常,但在创建 QApplication 类之后,它不再起作用了。请注意,进一步使用 QApplication 来构建GUI并使用它做很多复杂的事情。目前唯一不起作用的是 strptime

知道出了什么问题吗?

2 个答案:

答案 0 :(得分:1)

我可以重现你的问题:在调用QtWidget后,

print(datetime.datetime.strptime('Tue', '%a'))

导致错误。

如果我在QtWidget之后执行

print(datetime.datetime.strptime('Die', '%a')) 这很有效。

我位于瑞士,因此德语中的 Die 相当于 Tue

似乎Qt以某种方式对区域设置产生影响,因为%A和%a评估当地工作日的名称(Datetime)。也许Qt专家可以更详细地解释,正在进行的是什么。

答案 1 :(得分:0)

为了详细说明Patrick的好答案,我现在找到了一种方法来撤销QT强制执行的本地化

import sys
import datetime as datetime
import locale

from PyQt5 import QtWidgets

## Start the QT window
print(datetime.datetime.strptime('Tue', '%a'))
app = QtWidgets.QApplication(sys.argv)
locale.setlocale(locale.LC_TIME, "en_GB.utf8")
print(datetime.datetime.strptime('Tue', '%a'))
#sys.exit(app.exec_())