简体   繁体   中英

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

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.

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.

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

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

import time 

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

That's what you should have

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM