简体   繁体   English

将日期划分为日,月和年

[英]Divide date as day,month and year

l have 41 year-dataset and l would like to do some calculations by using these dataset but for this, l need to divide the date into day, month and year respectively. 我有41个年份数据集,并且希望使用这些数据集进行一些计算,但是为此,我需要将日期分别划分为日,月和年。

example dataset(csv file data) 示例数据集(csv文件数据)

 date      stations     pcp
1.01.1979   6   1.071
2.01.1979   6   5.909
3.01.1979   6   9.134
1.01.1979   5   1.229
2.01.1979   5   0.014
3.01.1979   5   3.241

l need to convert these data in this: 我需要这样转换这些数据:

day  month   year   stations   pcp
 1    01    1979     6         1.071
 2    01    1979     6         5.909
 3    01    1979     6         9.134

when l run code , it stops and l have to close it. 当我运行代码时,它将停止并必须将其关闭。 No error message. 没有错误讯息。 how can l correct this? 我该如何纠正? lma fresh user and probably ,there are many mistakes. lma新用户,也许有很多错误。 l hope l can learn my mistake here.l made two try and lm not sure which one is correct here is my code: 我希望可以在这里学到我的错误。我做了两次尝试,但我不确定哪一个是正确的,这是我的代码:

from datetime import date, datetime, timedelta,time
import csv
import numpy as np

a=[]
dd=[]
mm=[]
yy=[]
with open('p2.csv') as csvfile:
    x=[]
    reader = csv.DictReader(csvfile,fieldnames=("date","stations","pcp"),delimiter=';', quotechar='|')
    for row in reader:
       x.append(row["date"])

#try1
for i in range(len (x)):
   day,month,year=a.split(x[i])
   d=int(day)
   m=int(month)
   y=int(year)
   dd.append(d)
   mm.append(m)
   yy.append(y)



#try2
"""for i in range(len(x)):
   an=x[i]
   y=datetime.datetime.strftime(an, '%Y')
   d=datetime.datetime.strftime(an, '%d')
   m=datetime.datetime.strftime(an, '%m')
   dd.append(d)
   mm.append(m)
   yy.append(y)"""

There are a few problems: 有几个问题:

  1. Your delimiter should be a comma instead of a semicolon if it's a CSV. 如果是CSV,则分隔符应为逗号而不是分号。
  2. You are splitting on a date string instead of a delimiter when you call a.split(x[i]) . 当您调用a.split(x[i])时,您正在分割日期字符串而不是分隔符。 You probably want to split on a . 您可能想对进行拆分. , since that's what's separating the date fields. ,因为那是分隔日期字段的原因。

Without changing too much code, the following code works for me. 在不更改太多代码的情况下,以下代码对我有用。 It wasn't clear from your question what you want to actually do with the data, but I tried to demonstrate how you would get it. 从您的问题尚不清楚您实际上想对数据做些什么,但是我试图演示如何获得数据。

import csv

with open('p2.csv') as csvfile:
    reader = csv.DictReader(
        csvfile, fieldnames=('date', 'stations', 'pcp'), delimiter=',', quotechar='|')
    next(reader)  # skip header row
    x = [row['date'] for row in reader]

for date_str in x:
    day, month, year = date_str.split('.')
    print(day, month, year)

Output : 输出

1 01 1979
2 01 1979
3 01 1979
1 01 1979
2 01 1979
3 01 1979

this script will get you a list of lists with your values and will also write the final list into a csv. 该脚本将为您提供带有值的列表列表,还将最终列表写入csv。

import csv

with open('p2.csv') as csvfile:
    x=[]
    reader = csv.reader(csvfile,delimiter=',', quotechar='|')
    for num, row in enumerate(reader):
      for i, item in enumerate(row):
        if i ==0:
          yy = []
          d, m, y = item.split('.')
          yy.append(d)
          yy.append(m)
          yy.append(y)

        else:
          yy.append(item)
      x.append(yy)
    print x       

with open('output.csv', 'wb') as csvfile:
    datawriter = csv.writer(csvfile,delimiter=',', quotechar='|')
    for datarow in x:
      datawriter.writerow(datarow)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM