【问题标题】:How to split a date column into day/month/year columns using python如何使用python将日期列拆分为日/月/年列
【发布时间】:2021-12-17 02:31:36
【问题描述】:

我有一个 csv 文件,其中只有一列“日期”格式为整数:

date
20181231
20190107
20210329
...

解决方案是将整数分成不同的列来表示日、月、年和季度,例如:

date day month year quarter
20181231 31 12 2018 4
20190107 07 01 2019 1
20210329 29 03 2021 2
... ... ... ... ...

我会很感激每一种解决方案,但我应该使用 python 程序使用 pandas 库来解决它。

所以我写了这样的东西:

import csv
reader = csv.reader(open('date.csv', 'r'))
writer = csv.writer(open('datesplit.csv', 'w'))

for line in reader: 
    year = line[0][:3]
    month = line[0][4:5]
    day = line[0][6:]

    writer.writerow(year)
    writer.writerow(month)
    writer.writerow(day)

这不是你可以想象的,

感谢您的帮助

【问题讨论】:

  • 欢迎来到 Stack Overflow!您似乎在要求某人为您编写一些代码。 Stack Overflow 是一个问答网站,而不是代码编写服务。请see here学习如何写出有效的问题。
  • 我看到 python 已标记,但没有任何 Python 代码行;因此,我的反对意见。
  • 到目前为止你尝试了什么?

标签: python csv datetime text


【解决方案1】:

你可以使用日期时间:

import csv
import datetime

csvreader = csv.reader(open('date.csv', 'r'))
csvwriter = csv.writer(open('datesplit.csv', 'w'))

next(csvreader)
csvwriter.writerow(['date', 'day', 'month', 'year', 'quarter'])

for line in csvreader: 
    mydate = datetime.datetime.strptime(line[0], '%Y%m%d')
    csvwriter.writerow([line, mydate.day, mydate.month, mydate.year, (mydate.month-1)//3 + 1 ])

更多季度信息:Is there a Python function to determine which quarter of the year a date is in?

更多关于python中csv的信息:https://docs.python.org/3/library/csv.html

【讨论】:

    猜你喜欢
    • 2019-02-20
    • 2016-02-20
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    相关资源
    最近更新 更多