EP1986
EP1986

Reputation: 873

convert date from numpyarray into datetime type -> getting mystic error

I load a file f with the numpy.loadtxt function and wanted to extract some dates. The date has a format like this: 15.08. - 21.08.2011

numpyarr = loadtxt(f, dtype=str, delimiter=";", skiprows = 1)  

alldate = numpyarr[:,0][0]

dat = datetime.datetime.strptime(alldate,"%d.%m. - %d.%m.%Y")

And here is the whole error:

Traceback (most recent call last):
  File "C:\PYTHON\Test DATETIME_2.py", line 52, in <module>
    dat = datetime.datetime.strptime(alldate,"%d.%m. - %d.%m.%Y")

  File "C:\Python27\lib\_strptime.py", line 308, in _strptime
    format_regex = _TimeRE_cache.compile(format)

  File "C:\Python27\lib\_strptime.py", line 265, in compile
    return re_compile(self.pattern(format), IGNORECASE)

  File "C:\Python27\lib\re.py", line 190, in compile
    return _compile(pattern, flags)

  File "C:\Python27\lib\re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: redefinition of group name 'd' as group 3; was group 1

Does somebody have an idea was going on?

Upvotes: 1

Views: 401

Answers (1)

tktk
tktk

Reputation: 11734

A datetime holds a single date & time, while your field contains two dates and trys to extract them into a single variable. Specifically, the error you're getting is because you've used %d and %m twice.

You can try something along the lines of:

a = datetime.datetime.strptime(alldate.split('-')[0],"%d.%m. ")
b = datetime.datetime.strptime(alldate.split('-')[1]," %d.%m.%Y")
a = datetime.datetime(b.year, a.month, a.day)

(it's not the best code, but it demonstrates the fact that there are two dates in two different formats hiding in your string).

Upvotes: 1

Related Questions