1

I've been banging my head against a wall with the following error:

time
Traceback (most recent call last):
  File "csvtest.py", line 37, in <module>
    date = time.strptime(datestring, "%Y-%m-%d %H:%M:%S")
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 454, in _strptime_time
    return _strptime(data_string, format)[0]
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data 'time' does not match format '%Y-%m-%d %H:%M:%S'

The input is a row from a file with the format -- the year is purposefully junk data:

3354-03-16 15:30:00
3354-03-16 16:00:00
3354-03-16 16:30:00
3354-03-16 16:30:00

The code I'm using is below:


import sys
import csv
from datetime import datetime
import time

filename = open('data.csv', 'rb')


spam = csv.reader(filename, delimiter=',')
for row in spam:

    datestring = row[4] 
    print datestring
    date = time.strptime(datestring, "%Y-%m-%d %H:%M:%S")
filename.close()
2
  • time.strptime('3354-03-16 16:30:00', "%Y-%m-%d %H:%M:%S") returns time.struct_time(tm_year=3354, tm_mon=3, tm_mday=16, tm_hour=16, tm_min=30, tm_sec=0, tm_wday=5, tm_yday=75, tm_isdst=-1) are you sure datestring contains the data above? Commented Feb 6, 2012 at 16:30
  • Fix implement was simply to add "next(spam)" line between spam definition and for row in spam block. Commented Feb 6, 2012 at 16:44

2 Answers 2

6

There's nothing wrong with the format or the date strings.

I bet your file has a header row, and the code chokes on that.

Sign up to request clarification or add additional context in comments.

4 Comments

Works for me too, and when I introduce a header row this is exactly the error I get.
You guys are fast! Thank you. I'm new to Python and realized my pre-process script did keep the headers.
@LillianMilagrosCarrasquillo: The mention of 'time' in the error message was a bit of a giveaway ;-)
@LillianMilagrosCarrasquillo: when people present a short code exhibiting the problem that can be cut-and-pasted for people to try out, and they post exactly the error message they see, they make it easy to figure out problems and therefore they get quick responses. Don't forget to accept aix's answer if you found it helpful!
1

You can see from the error itself what the problem is:

ValueError: time data 'time' does not match format '%Y-%m-%d %H:%M:%S'

So you pass as input a string 'time', probably the header of the csv file. Just skip that row.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.