安装python补丁以在Pycharm中检索1900年之前的日期

时间:2017-12-04 19:47:15

标签: python datetime pycharm

下面显示的我的python代码不会在1900年之前检索任何日期。我了解到这是datetime.strptime()的限制。

我试图遵循类似帖子Is there any way to use a strftime-like function for dates before 1900 in Python?中提到的一些解决方法,但对我来说,它们似乎有点复杂。我还了解到有一个补丁可以解决这个问题。 https://bugs.python.org/file10253/strftime-pre-1900.patch

我尝试通过将补丁复制到文本文件来在Pycharm中安装补丁,但是我收到以下错误消息。有关如何成功运行补丁以获取1900年之前的日期的任何想法?

Pycharm Patch Error Screenshot

我的代码:

from datetime import datetime

import csv

with open('train.csv', 'r') as f_input, open('sample.txt', 'w') as f_output:
csv_input = csv.reader(f_input)
csv_output = csv.writer(f_output)

for row in csv_input:
    for date_format in ['%Y']:
        try:
            converted = datetime.strptime(row[3], date_format)
            csv_output.writerow([row[0], row[1], row[2], converted.strftime(date_format)])
        except ValueError:
            pass

1 个答案:

答案 0 :(得分:1)

我意识到这不是你提出的问题,但我会把它放在那里,因为我假设如果链接问题的答案太复杂而无法遵循,那么成功修补问题的想法是可能不切实际。

您所看到的限制出现在Python2

Python 2.7.12 (default, Nov 20 2017, 18:23:56) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> d = datetime(1899, 1, 1)
>>> d.strftime('%Y-%m-%d')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: year=1899 is before 1900; the datetime strftime() methods require year >= 1900

somewhat rectified in Python3.2, and fully rectified in Python3.3及以后:

Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> d = datetime(1899, 1, 1)
>>> d.strftime('%Y-%m-%d')
'1899-01-01'

解析工作也是如此:

>>> d = datetime.strptime('0113-01-01','%Y-%m-%d')
>>> d
datetime.datetime(113, 1, 1, 0, 0)
>>> d.isoformat()
'0113-01-01T00:00:00'
>>> d.strftime('%Y-%m-%d')
'113-01-01'

因此,如果这是一个可接受的选项,您可以切换到Python3.3 +,您将不会遇到此问题。