Python 3.6 csv str类型日期或time.struct_time类型与datetime.date数据类型进行比较

时间:2018-01-18 17:48:18

标签: python-3.x csv date type-conversion

我有一个带日期列的csv文件。我想将该日期与当前日期进行比较。当我使用time模块获取当前日期时,它是一个datetime.date类型,但当我使用转换方法@unwind posted here时,我的列的数据类型是time.struct_time,我收到一个错误。

import csv
import time
from datetime import datetime
import uuid
present = datetime.today().date()
with open(r'FilePath','r',newline='') as f:
        # skip header line
        next(f)
        r = csv.reader(f)
        for row in r:
            if len(row[29])>1:
                newdate2 = time.strptime(row[29], "%m/%d/%Y").strftime("%Y-%m-%d")

错误:

Traceback (most recent call last):
  File "C:/FilePath/DateCompare.py", line 15, in <module>
    newdate2 = time.strptime(row[29], "%m/%d/%Y").strftime("%Y-%m-%d")
AttributeError: 'time.struct_time' object has no attribute 'strftime'

索引可以组合成一个字符串,但我无法弄清楚如何转换为datetime.date进行比较。

将列转换为格式化字符串:

import csv
import time
from datetime import datetime
import uuid
present = datetime.today().date()

with open(r'FilePath','r',newline='') as f:
        # skip header line
        next(f)
        r = csv.reader(f)
        for row in r:
            if len(row[29])>1:
                newdate2 = time.strptime(row[29], "%m/%d/%Y")
                newdate3 = ('{}-{}-{}'.format(newdate2[0],newdate2[1],newdate2[2])) 

示例字符串输出:

2018-2-1
2018-2-1

1 个答案:

答案 0 :(得分:0)

使用.now()而不是.today.date将我的“present”变量变为datetime.datetime格式并使用datetime.strptime(row [29],“%m /%d /%Y”)得到了我的单元格值到datetime.datetime,以便我可以将当​​前日期与文件中的日期进行比较。

import csv
from datetime import datetime
present = datetime.now()
with open(r'InputFilePath','r',newline='') as f:
    with open(r'DestinationFilePath','w', newline ='') as f1:
        next(f)
        w = csv.writer (f1)
        r = csv.reader(f)
        for row in r:
            if len(row[29])>1:
                newdate2 = datetime.strptime(row[29], "%m/%d/%Y")
                row[29] = newdate2
                if row[29]>present:
                    w.writerow(row)
                else:
                    continue