-4

i want to put datetime into a array, is there a solution? i am newbie

import csv
from datetime import datetime    
date = []
price = []
tdate = []
tprice = []

with open('TSLA.csv', 'r') as csvfile:
    csvR = csv.reader(csvfile)
    next(csvR)  # skipping column names
    for i,row in enumerate(csvR):
        row_date = datetime.strptime(row[0], "%m/%d/%Y")
        date.append(float(row_date))
        price.append(float(row[5]))

if you want to see the error:

File "csvtest.py", line 14, in <module>
    date.append(float(row_date))
TypeError: float() argument must be a string or a number, not 'datetime.datetime'

update

with open('TSLA.csv', 'r') as csvfile:
    csvR = csv.reader(csvfile)
    next(csvR)  # skipping column names
    for i,row in enumerate(csvR):
        ts = time.strptime(row[0], "%m/%d/%Y")
        time.mktime(ts)
        date.append(float(ts))
        price.append(float(row[5]))

error:

TypeError: float() argument must be a string or a number, not 'time.struct_time'
johnson
  • 1
  • 1
  • 2

2 Answers2

1

Conversion to float is not very informative here. You can however convert the datetime object to a timestamp object.

Considering that row[0] holds a datetime object, something like below should work:

import time
timestamp = time.mktime((row[0].timetuple())

timestamp would be a UTC timestamp generated from your datetime object.

Update:

Observed that row[0] holds a date in string format.

>>> import time 
>>> ts = time.strptime("10/10/2018", "%m/%d/%Y")
>>> time.mktime(ts)
>>> 1539109800.0
Ankit Jaiswal
  • 22,859
  • 5
  • 41
  • 64
0

sloved

with open('TSLA.csv', 'r') as csvfile:
    csvR = csv.reader(csvfile)
    next(csvR)  # skipping column names
    for i,row in enumerate(csvR):
        date.append(datetime.strptime(row[0],'%m/%d/%Y'))
        price.append(float(row[5]))
        if(i >= 25):
            tdate.append(float(row[7]))
            tprice.append(float(row[5]))
            break
johnson
  • 1
  • 1
  • 2