Home > Net >  "re.error: redefinition of group name" when using strptime
"re.error: redefinition of group name" when using strptime

Time:08-03

I am trying to convert this string into date format:

import datetime
my_string = "202206051234555555"
convert_date = datetime.datetime.strptime(my_string, "%Y%M%d%H%M%S")

I am getting this error:

re.error, redefinition of group name 'M' as group 5; was group 2

Can someone help in converting this string type to date? I want only date and I dont want time at the end.

CodePudding user response:

The two main problems you had in your code were

  1. You used %M (which stands for minutes) at the beginning instead of %m (which stands for months).
  2. You tried to fit 555555 into %s (which takes only two digits i.e. doesn't take milliseconds), so I added %f to take care of that.

This should do the trick:

import datetime
my_string = "202206051234555555"
convert_date = datetime.datetime.strptime(my_string, "%Y%m%d%H%M%S%f")
  • Related