Deepak V
Deepak V

Reputation: 319

How do find difference between 2 dates in Python?

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.

Upvotes: 0

Views: 73

Answers (2)

Deepak V
Deepak V

Reputation: 319

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"')

Upvotes: 0

blhsing
blhsing

Reputation: 106435

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"')

Upvotes: 1

Related Questions