0

This question is w.r.t Python 2.7.

I have the following time data in a CSV file - the format is MM-dd-yyyy HH:mm:ss:ffffff. I would like to find difference between 2 dates. The difference between 2 dates is usually in milliseconds.

I tried to use the following API to convert the str to a datetime object,

time_info = datetime.strptime(time_data_from_csv, '%m-%d-%Y %H:%M:%S')

I get the following error -

ValueError: time data '"12-31-2018 12:21:12.315948"' does not match format '%m-%d-%Y %H:%M:%S'

I also tried - '%m-%d-%Y %H:%M:%S.%f', to no avail (not sure if it was the right usage). Here, time_data_from_csv is a string variable. Any pointers would be appreciated.

2
  • I'm confused, you state the timestamp is in one format, try to use a different, un-matching format to parse it, and get an error saying it doesn't match. What's the question? (And you state the CSV data separates date components with "/", which doesn't line up with the code or example data.) Commented Feb 9, 2019 at 13:24
  • I updated my question, please check. I tried with the millisecond formatter too "%f". Did not work. I am suspecting if the single quote around the string data is '"12-31-2018 12:21:12.315948"', is causing trouble. Commented Feb 9, 2019 at 13:31

2 Answers 2

1

You should include the double quotes in the format string since your time_data_from_csv variable has them, according to the error message:

time_info = datetime.strptime(time_data_from_csv, '"%m-%d-%Y %H:%M:%S.%f"')
Sign up to request clarification or add additional context in comments.

2 Comments

Hi blhsing, thanks for that. As I mentioned in my updated question, that does not seem to work when I use the variable. The error has a single quote ' and double quote around the date, is it the problem?
Yep, as you rightly pointed out. That was the trouble. I fixed it. I answered it too. Thanks for your quick response, appreciate it!
0

I found the culprit. As I suspected, somehow the double-quotes were causing the trouble. I solved it by adding double-quotes to my format string. Thanks for all your attention and help!

datetime.strptime(time_data_from_csv, '"%m-%d-%Y %H:%M:%S.%f"')

1 Comment

"Somehow"? They're characters not in the format specifier.

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.