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'
Asked By: Victor

||

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:

  1. Fix (remove) the quotes in your source data and use your original code
  2. Strip the quotes from the string before trying to parse it:

    dates.append(datetime.strptime(line1.strip('"'),"%Y-%m-%d %H:%M:%S"))
    
  3. Change your date format string to look for a date containing double quotes:

    dates.append(datetime.strptime(line1,'"%Y-%m-%d %H:%M:%S"'))
    
  4. Use Python’s csv library which may handle reading csv files better
Answered By: akiller
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.