Problems in converting string to datetime object with strptime
Question:
I’m trying to convert a time string into a datetime object with strptime. The problem is that I’m getting a format error from string to datetime object.
I don’t understand why this format is not appropriate for my data.
import numpy as np
from datetime import datetime
Vent_date = np.array([b'"2018-06-28 15:00:00"', b'"2018-06-28 15:00:00"'], dtype='|S21')
dates = []
for line in Vent_date:
line1 = line.decode('utf-8')
dates.append(datetime.strptime(line1,'%Y-%m-%d %H:%M:%S'))
I get:
ValueError: time data '"2018-06-28 15:00:00"' does not match format '%Y-%m-%d %H:%M:%S'
Answers:
If you notice the error contains double quotes wrapped in single quotes. So it looks like your source data has double quotes in it which is why it is failing.
A few simple solutions:
- Fix (remove) the quotes in your source data and use your original code
-
Strip the quotes from the string before trying to parse it:
dates.append(datetime.strptime(line1.strip('"'),"%Y-%m-%d %H:%M:%S"))
-
Change your date format string to look for a date containing double quotes:
dates.append(datetime.strptime(line1,'"%Y-%m-%d %H:%M:%S"'))
- Use Python’s csv library which may handle reading csv files better
I’m trying to convert a time string into a datetime object with strptime. The problem is that I’m getting a format error from string to datetime object.
I don’t understand why this format is not appropriate for my data.
import numpy as np
from datetime import datetime
Vent_date = np.array([b'"2018-06-28 15:00:00"', b'"2018-06-28 15:00:00"'], dtype='|S21')
dates = []
for line in Vent_date:
line1 = line.decode('utf-8')
dates.append(datetime.strptime(line1,'%Y-%m-%d %H:%M:%S'))
I get:
ValueError: time data '"2018-06-28 15:00:00"' does not match format '%Y-%m-%d %H:%M:%S'
If you notice the error contains double quotes wrapped in single quotes. So it looks like your source data has double quotes in it which is why it is failing.
A few simple solutions:
- Fix (remove) the quotes in your source data and use your original code
-
Strip the quotes from the string before trying to parse it:
dates.append(datetime.strptime(line1.strip('"'),"%Y-%m-%d %H:%M:%S"))
-
Change your date format string to look for a date containing double quotes:
dates.append(datetime.strptime(line1,'"%Y-%m-%d %H:%M:%S"'))
- Use Python’s csv library which may handle reading csv files better