【问题标题】:Convert Alphanumerical Date String to Numerical Date String将字母数字日期字符串转换为数字日期字符串
【发布时间】:2018-07-21 16:14:53
【问题描述】:

我知道那里有类似的问题,但最简单的是使用 strptime 方法将字母数字日期字符串转换为 datetime 对象,这不是我想要的。我要做的就是像这样转换字符串。

可能输入的格式

December 7, 2015
October 24, 2018

期望的输出

2015-12-07
2018-10-24

我是怎么做的

""" funding_expiration[0] is equal to strings like 'December 7, 2015' """
funding_expiration = funding_expiration[0].text.split()
""" still need to convert Month (%B) to ## (%m) """
funding_expiration[1] = funding_expiration[1].replace(',', '')
# add padding to single digit days
if len(funding_expiration[1]) is 1:
    funding_expiration[1] = funding_expiration[1].zfill(1)
# format numerical date string
funding_expiration = funding_expiration[2] + '-' + funding_expiration[0] + '-' + funding_expiration[1]

我仍在尝试找出一种将月份的全名转换为相应数字的有效方法。我是 Python 新手,所以我想知道是否有更有效的方法来完成此任务?

【问题讨论】:

  • @Sarcoma 对不起,你是什么意思?我不在乎是上面的代码还是其他代码。但是,我宁愿不创建字典,因为这是我唯一需要这样做的时间
  • @Sarcoma 是的,我宁愿不使用库,因为这是整个脚本中唯一需要这样做的时间

标签: python date datetime datetime-format


【解决方案1】:

datetime.strptime 也适用于您的情况。您可以使用%B 指令来解析完整的月份名称。

import datetime

s = 'December 7, 2015'

date_string = str(datetime.datetime.strptime(s, '%B %d, %Y').date())

>>> date_string
'2015-12-07'

【讨论】:

  • 完美。谢谢。只要它允许我,我就把它标记为答案
【解决方案2】:

这是使用第 3 方dateutil 的解决方案:

from dateutil import parser

L = ['December 7, 2015', 'October 24, 2018']

res_str = [parser.parse(x).strftime('%Y-%m-%d') for x in L]

['2015-12-07', '2018-10-24']

【讨论】:

  • 不太喜欢使用框架,因为我只需要在整个脚本中执行一次。我还为别的东西导入了datetime,所以...