python对日期型数据排序_在python中按日期对csv对象进行排序

I am trying to read and sort a csv file that has data that looks like

Date Open High Low Close Volume

27-Mar-12 8.25 8.35 8.17 8.19 9801989

26-Mar-12 8.16 8.25 8.12 8.24 8694416

23-Mar-12 8.05 8.12 7.95 8.09 8149170

I do this with

import csv

data = csv.reader(open('data.csv','r'))

To sort data by Date. I do:

sorteddata = sorted(data,key=operator.itemgetter(1),reverse=False)

The problem is, that it sorted the dates by reading them as String and not as dates. So the data is sorted like so,

['3-Aug-11', '7.06', '7.23', '6.84', '7.16', '31583617']

['3-Feb-12', '7.02', '7.12', '6.98', '7.08', '15318044']

['3-Jan-12', '5.53', '5.59', '5.44', '5.48', '12678923']

['3-Jun-11', '8.09', '8.17', '7.92', '7.97', '21273812']

['3-May-11', '9.00', '9.04', '8.63', '8.80', '17356005']

Does anybody know how to sort by dates?

解决方案

Use datetime.strptime to get a datetime from the date field:

from datetime import datetime

data = sorted(data, key = lambda row: datetime.strptime(row[0], "%d-%b-%y"))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值