2017-07-20 93 views
-1

以下是我的數據示例(並且在我的csv文件中有很多這種數據的行),我需要一個程序可以分隔連字符,冒號和字母「T」,以便我可以打印出所需日期的行(例如12月31日)。我已經有了一個可以過濾掉年份和月份的代碼,但是我現在無法分割T /將T設置爲分隔符。Python:如何使用多個分隔符在一行中拆分逗號,冒號和字母

AC2_AC1,382,3,2015-12-31T22:40:00-05

import csv 

desiredMonth = 12 
with open('extractedStreet2015.csv', 'r') as csvfile: 
    content = csv.reader(csvfile, delimiter=',') 
    for row in content: 
     month = int(row[3].split('-')[1]) 
     if month == desiredMonth: 
      print(row) 

我如何寫代碼,這樣我也可以分割冒號和字母 「T」? (PS我是新來的Python這樣的解釋,將不勝感激)

EDITED

當我嘗試運行下面的程序:

import csv 
import isodate 

desiredHour = 12 

with open('bt_2015.csv', 'r') as csvfile: 
    content = csv.reader(csvfile, delimiter=',') 
    for row in content: 
     date = isodate.parse_datetime(content[3]) 
     if date.hour == desiredHour: 
      print(row[1]) 

出現此消息:

Traceback (most recent call last): 
    File "C:\Python36\hour.py", line 10, in <module> 
    date = isodate.parse_datetime(content[3]) 
TypeError: '_csv.reader' object is not subscriptable 

我能做些什麼來解決這個問題?

+1

你REALI你的日期/時間是一個標準的ISO 8601格式化字符串 – cmd

+0

使用'datetime'模塊來解析你的日期字符串。 –

+0

對不起,我沒有意識到,就像我說的,我是編程新手(剛剛在一週前開始) – Melissa

回答

1

如何

import isodate 
data = 'AC2_AC1,382,3,2015-12-31T22:40:00-05' 
parts = data.split(',') 
isodate.parse_datetime(parts[3]) 
datetime.datetime(2015, 12, 31, 22, 40, tzinfo=<FixedOffset '-05'>) 

現在你有一個標準的Python的datetime對象

+0

你可以,但'isodate'處理所有iso 8601格式變體。 – cmd

+0

我如何得到isodate? – Melissa

+0

假設你有點子:'PIP安裝isodate' – cmd

0

使用你的例子:

# filename: test_data.txt 
AC2_AC1,382,3,2015-12-31T22:40:00-05 

這是我會做什麼....

$ pip install python-dateutil 

參見: pip

參見:namedtuple

參見:python-dateutil

#!/usr/bin/env python 
# filename: test.py 
import csv 
from collections import namedtuple 

from dateutil import parser 

# I don't know your field names, but maybe you can supply them. 
StreetRecord = namedtuple('StreetRecord', 'ac_field, num01, num02, timestamp') 


def extract_records(filepath, month): 
    """Captures records that match the month 

    Args: 
     filepath (str): path to file 
     month (int): value of month to filter on 

    Yields: 
     StreetRecord: each street record that matches the month 
    """ 
    with open(filepath, 'r') as stream: 
     content = csv.reader(stream, delimiter=',') 
     for record_data in content: 
      record = StreetRecord(*record_data) 
      # example timestamp: 2015-12-31T22:40:00-05 
      timestamp = parser.parse(record.timestamp) 
      if timestamp.month == month: 
       yield record 


if __name__ == '__main__': 
    for record in extract_records('test_data.txt', 12): 
     print(record) 

然後運行它...

python test.py 

,你會看到:

StreetRecord(ac_field='AC2_AC1', num01='382', num02='3', timestamp='2015-12-31T22:40:00-05') 
相關問題