-3

I have a csv file with just one column 'date' formatted as integer:

date
20181231
20190107
20210329
...

The solution would be to split the integer into different columns to represent day, month, year and quarter, like:

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

I would appreciate every kind of solution but I should resolve it using a python program without using pandas library.

So I write something like this:

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)

it is not working a you can imagine,

Thanks for helping

pasq
  • 21
  • 6
  • Welcome to Stack Overflow! You seem to be asking for someone to write some code for you. Stack Overflow is a question and answer site, not a code-writing service. Please [see here](http://stackoverflow.com/help/how-to-ask) to learn how to write effective questions. – Yevhen Kuzmovych Nov 02 '21 at 15:00
  • I see `python` tagged, but no lines of python code; thus, my downvote. – rv.kvetch Nov 02 '21 at 15:01
  • What have you tried so far? – Daweo Nov 02 '21 at 15:05

1 Answers1

0

You can use datetime:

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 ])

More information about quarter: Is there a Python function to determine which quarter of the year a date is in?

More information about csv in python: https://docs.python.org/3/library/csv.html

ilizaran
  • 66
  • 5