You could use a try..except
to first try one format, and if it does not work, catch the exception and try the other format:
import datetime as DT
import numpy as np
def timeConv(x):
try:
return DT.datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f')
except ValueError as err:
return DT.datetime.strptime(x, '%Y-%m-%d %H:%M:%S')
time = np.genfromtxt(file, dtype='object', delimiter=',', skip_header=4,
usecols=(0), converters = {0: timeConv})
The function, timeConv
is passed to genfromtxt
the same way you passed the lambda
.
The dateutil module has a date string parser which does not require you to specify the exact format of the date string. So using dateutil you could simply write
import dateutil.parser as dparser
import numpy as np
time = np.genfromtxt(file, dtype='object', delimiter=',', skip_header=4,
usecols=(0), converters = {0: dparser.parse})
Note that although dparser.parse
is very easy to use, there are some ambiguous date strings like 2013-8-9
(August 8 or Sept 9?) which require more care. Be sure to read up on the dayfirst
and yearfirst
parameters so you can control the parser's behavior.