如何使用Python从excel文件中的日期列中减去固定日期?

2024-09-26 22:53:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个以下格式的文件:

name           date
sam          21/1/2003
bil          5/4/2006
sam          4/7/2009
Mali         24/7/2009
bil          13/2/2008
etc...

我想设置一个固定的日期,例如:1/1/2003,从我的固定日期中减去所有的日期,然后除以周,找出哪些名字是在哪个星期注册的,然后把它们放在一个集合中。所以我想得到以下最终结果:

^{pr2}$

我已经编写了下面的python脚本,但它不起作用。我有以下错误:

 val=set(start_date-'date(data.files.datetime)')
TypeError: unsupported operand type(s) for -: 'int' and 'str'

有人知道为它编写代码的最佳方法是什么吗?在

import pprint
import csv


with open('d:/Results/names_info.csv', 'r') as csvfile:
    start_date= 1/1/2003
    filereader=csv.reader(csvfile,'excel')
    for row in filereader:
         for name in row:
             key=name
             val=set(start_date-'date(data.files.datetime)')
             datedict[key]=val


pprint.pprint (datedict)

Tags: csvcsvfilenameimportfordatadatetimedate
2条回答

您的代码中有几个错误:

  1. 不忽略csv文件的第一行,其中包含“name”和“date”。在
  2. 使用字符串存储日期,而不是date类型。在
  3. 试图从另一个字符串中减去一个字符串。在
  4. 修改datedict中的项,而不首先检查它们是否存在。在
  5. 2003年1月1日的斜杠将被视为除号,结果是0。在

以下是修复这些错误后代码的外观:

import csv
from collections import defaultdict
import datetime
from datetime import date
import math

def weeks(filename, start_date):
    # The defaultdict class will create items when a key is accessed that does
    # not exist
    datedict = defaultdict(set)
    with open(filename, 'r') as csvfile:
        filereader = csv.reader(csvfile, 'excel')
        read_header = False
        for row in filereader:
            # Ignore the first row of the file
            if not read_header:
                read_header = True
                continue

            # Strip out any whitespace
            cells = [col.strip() for col in row]
            name = cells[0]
            date_str = cells[1]

            # Parse the date string into a date
            row_date = datetime.datetime.strptime(date_str, '%d/%m/%Y').date()

            # Calculate the difference between dates
            delta = start_date-row_date
            # Convert from days to weeks, you could use math.floor() here if
            # needed
            delta_weeks = int(math.ceil(delta.days / 7.0))

            datedict[name].add(delta_weeks)

    return datedict

date_dict = weeks('a.csv', start_date=date(year=2013, month=1, day=1))
for name, dates in date_dict.iteritems():
    print name, list(dates)

打印出来:

^{pr2}$

你应该能想出办法让它打印“周”。在

您肯定希望使用标准库中的datetime模块。计算周差的一种快速而肮脏的方法可以是:

import datetime

start_date = datetime.date(2003,1,1)  # (YYYY,MM,DD)
another_date = datetime.date(2003,10,20)

difference = start_date - another_date  # another datetime object
weeks_between = difference.days / 7 + 1 # integer division, first week = 1

另外,如果您想要一个dictlist,请将datedict[key]=val替换为

^{pr2}$

另外,如果您希望列表具有格式为week1、week12等的字符串,那么只需使用

val = 'week%d' % val

相关问题 更多 >

    热门问题