0

I'm having trouble converting a string to data format. I'm using the time module to convert a string to the YYYY-MM-DD format. The code below is what I've tried but I get the following error.

sre_constants.error: redefinition of group name 'Y' as group 5; was group 3

Here is the code

import time 

review_date = "April 18, 2018"
review_date = time.strptime(review_date, '%m %d %Y %I:%Y%m%d')
1
  • 1
    Your format is not correct. The date you are passing is in this format: '%B %d, %Y'. If you use month name, then its %B instead of %m. Commented Apr 19, 2018 at 22:56

5 Answers 5

1

Firstly, the error is because you're using %Y, %m, and %d twice in your time.strptime() call.

Secondly, you're using the wrong format. The format you pass to strptime() has to match the format of the date / time string you pass, which in this case is: %B %d, %Y.

This is a good reference on the different format types.

Sign up to request clarification or add additional context in comments.

1 Comment

The problem is much more fundamental than this!
1

I normally use datetime for this:

from datetime import datetime
review_date = "April 18, 2018"
review_date = datetime.strptime(review_date, '%B %d, %Y').strftime('%Y-%m-%d')

This code returns review_date = '2018-04-18'. See https://docs.python.org/3/library/datetime.html The date format for April is %B. strptime() converts to a datetime object, .strftime() converts the datetime object to a string.

Comments

0

time.strptime() is for parsing strings into date/time structures. It takes two arguments, the string to be parsed and another string describing the format of the string to be parsed.

Try this:

time.strptime("April 18, 2018", "%B %d, %Y")

... and notice that "%B %d, %Y" is:

  1. Full locale name of the month ("April")
  2. [Space]
  3. Date of the month (18)
  4. [Comma]
  5. [Space]
  6. Four digit year (2018)

The format string specification that you provided bears no resemblance to the formatting of your date string.

These "magic" formatting codes are enumerated in the documentation for time.strftime()

Comments

0
review_date = time.strptime(review_date, '%B %d, %Y')

Comments

0
import time 

review_date = "April 18, 2018"
review_date = time.strptime(review_date, '%B %d, %Y')

That's what you should have

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.