jhaywoo8
jhaywoo8

Reputation: 767

Converting string in python to date format

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')

Upvotes: 0

Views: 171

Answers (5)

manu
manu

Reputation: 1

import time 

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

That's what you should have

Upvotes: 0

eclark
eclark

Reputation: 491

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.

Upvotes: 1

Manuel Hess
Manuel Hess

Reputation: 139

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

Upvotes: 0

Jim Dennis
Jim Dennis

Reputation: 17500

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()

Upvotes: 0

Colin Ricardo
Colin Ricardo

Reputation: 17249

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.

Upvotes: 1

Related Questions