将日期字符串转换为YYYYMMDD

时间:2011-08-04 13:07:49

标签: python

我有一堆这样的日期字符串: -

30th November 2009
31st March 2010
30th September 2010

我希望他们这样: -

YYYYMMDD

目前我这样做: -

  parsed_date = "30th November 2009"
  part = parsed_date.split(' ')
  daymonth = part[0].strip(string.ascii_letters)
  mytime = daymonth+" "+part[1]+" "+part[2]
  time_format = "%d %B %Y"
  cdate = time.strptime(mytime, time_format)
  newdate = str(cdate[0])+str(cdate[1])+str(cdate[2])

它有效,但我确信有更好的方法......

3 个答案:

答案 0 :(得分:13)

尝试dateutil

from dateutil import parser

dates = ['30th November 2009', '31st March 2010', '30th September 2010']

for date in dates:
    print parser.parse(date).strftime('%Y%m%d')

输出:

20091130
20100331
20100930

或者如果您想使用标准datetime模块执行此操作:

from datetime import datetime

dates = ['30th November 2009', '31st March 2010', '30th September 2010']

for date in dates:
    part = date.split()
    print datetime.strptime('%s %s %s' % (part[0][:-2]), part[1], part[2]), '%d %B %Y').strftime('%Y%m%d')

答案 1 :(得分:5)

您可以使用strptime and strptime from the datetime module

的组合来完成此操作

我们遇到的问题是,内置格式支持30 November 2010但不支持30th November 2010等日期。因此,在下面的示例中,我使用a regular expression substitution来删除问题字符。 (正则表达式使用后视来查看“st”,“nd”,“rd”或“th”是否以数字开头,如果是,则将其替换为空字符串,从而将其从字符串中删除。 )

>>> import re
>>> from datetime import datetime
>>> mydate = "30th November 2009"
>>> mydate = re.sub("(?<=\d)(st|nd|rd|th)","",mydate)
>>> mydate
'30 November 2009'
>>> mydatetime = datetime.strptime(mydate,"%d %B %Y")
>>> mydatetime
datetime.datetime(2009, 11, 30, 0, 0)
>>> mydatetime.strftime("%Y%M%d")
'20090030'

答案 2 :(得分:1)

在python 3.7中,您可以使用isoformat()

>>> from datetime import datetime
>>> datetime.today().date().isoformat().replace("-", "")
'20190220'