mp3por
mp3por

Reputation: 1852

Datestring to date Python

I am trying to parse this string: '2017-02-28T23:00:00.000Z' into a python datetime object.

My code is

ev_begin_date = datetime.datetime.strptime('2017-02-28T23:00:00.000Z','%Y-%M-%dT%H:%M:%S.%Z' )

I get the following error:

 ev_begin_date = datetime.datetime.strptime('2017-02-28T23:00:00.000Z','%Y-%M-%dT%H:%M:%S.%Z' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 342, in _strptime
    format_regex = _TimeRE_cache.compile(format)
  File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 272, in compile
    return re_compile(self.pattern(format), IGNORECASE)
  File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 234, in compile
    return _compile(pattern, flags)
  File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 286, in _compile
    p = sre_compile.compile(pattern, flags)
  File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_compile.py", line 764, in compile
    p = sre_parse.parse(p, flags)
  File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_parse.py", line 930, in parse
    p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
  File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_parse.py", line 426, in _parse_sub
    not nested and not items))
  File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_parse.py", line 813, in _parse
    raise source.error(err.msg, len(name) + 1) from None
re.error: redefinition of group name 'M' as group 5; was group 2 at position 105

What am I doing wrong ?

Upvotes: 0

Views: 43

Answers (1)

Adam.Er8
Adam.Er8

Reputation: 13403

try this:

ev_begin_date = datetime.datetime.strptime('2017-02-28T23:00:00.000Z','%Y-%m-%dT%H:%M:%S.%fZ' )

fixed:

  • you originally used %M for the month as well. it should be %m
  • the millisecond part is %f, the Z is literal (it appears in the string)

you can check out strptime's docs for a complete reference on all format options

Upvotes: 2

Related Questions