简体   繁体   中英

(python) usual ValueError in parsing a date using datetime

I have read all other questions and checked thoroughly my script, but the error persists.

my test.txt file contains:

89.02 , 22/12/2016 
90.63 , 02/01/2017

where the order of the date is: day/month/year, and this is my script:

import numpy as np
from datetime import datetime
from matplotlib.dates import datestr2num
datefunc = lambda x: datestr2num(datetime.strptime(x, '%d/%m/%Y'))
values, date = np.loadtxt('test.txt', delimiter=',', unpack=True, converters = {1 : datefunc})

and I get the

ValueError: time data ' 22/12/2016 ' does not match format '%d/%m/%Y'

Does someone see a mistake in there? Thank you, that will be very appreciated

The date data has extra space around it. Try stripping the date string before passing it to strptime :

datefunc = lambda x: datestr2num(datetime.strptime(x.strip(), '%d/%m/%Y'))

Bcecause you have spaces around your string x

You can either use strip() :

>>> datetime.strptime(x.strip(), '%d/%m/%Y')
datetime.datetime(2016, 12, 22, 0, 0)

Or add spaces to format param:

>>> datetime.strptime(x, ' %d/%m/%Y ')
datetime.datetime(2016, 12, 22, 0, 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM