简体   繁体   English

将 python 中的字符串转换为日期格式

[英]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.我正在使用时间模块将字符串转换为 YYYY-MM-DD 格式。 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. 首先,该错误是因为在time.strptime()调用中两次使用%Y%m%d

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 . 您传递给strptime()的格式必须与您传递的日期/时间字符串的格式匹配,在这种情况下为: %B %d, %Y

This is a good reference on the different format types. 是有关不同格式类型的很好的参考。

I normally use datetime for this: 我通常为此使用datetime

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'. 此代码返回review_date ='2018-04-18'。 See https://docs.python.org/3/library/datetime.html The date format for April is %B . 请参阅https://docs.python.org/3/library/datetime.html April的日期格式为%B strptime() converts to a datetime object, .strftime() converts the datetime object to a string. strptime()转换为日期时间对象, .strftime()将日期时间对象转换为字符串。

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

time.strptime() is for parsing strings into date/time structures. time.strptime()用于将字符串解析为日期/时间结构。 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: ...,请注意,“%B%d,%Y”为:

  1. Full locale name of the month ("April") 本月的完整语言环境名称(“ 4月”)
  2. [Space] [空间]
  3. Date of the month (18) 月份的日期(18)
  4. [Comma] [逗号]
  5. [Space] [空间]
  6. Four digit year (2018) 四位数年份(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() 这些“魔术”格式代码在time.strftime()文档中进行了枚举。

import time 

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

That's what you should have那才是你应该拥有的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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