如何将 python 中的字符串日期 (Jan 25, 2021) 转换为年月日 (2021-01-01)

How to convert string date (Jan 25, 2021) to y-m-d date (2021-01-01) in python

我有像 Jan 25, 2021 这样的字符串(一月、二月、三月、五月、六月、七月、八月、九月、十月、十一月、十二月),如何将其转换为 2021-01-25

我定义的函数如下:

def to_datetime(datestring):  
    
    #date = datetime.strptime(datestring, '%m.%d.%Y')
    #return date.strftime("%Y-%m-%d")
    
    return datetime.strptime(datestring, '%Y-%m-%d')

问题是月份词,所以也许我可以将字符串替换为月份数字,然后进行转换,但我卡住了

正如你在我的评论中看到的,你只需要使用正确的匹配面具就可以了。

您的日期字符串采用 %b %d, %Y 格式,因此您需要在 strptime() 中使用相同的掩码。考虑到这一点,像这样的函数就可以完成这项工作:

from datetime import datetime


def mdy_to_ymd(d):
    return datetime.strptime(d, '%b %d, %Y').strftime('%Y-%m-%d')

这是一个概念证明:


>>> from datetime import datetime
>>> 
>>> 
>>> def mdy_to_ymd(d):
...     return datetime.strptime(d, '%b %d, %Y').strftime('%Y-%m-%d')
... 
>>> mdy_to_ymd('Jan 25, 2021')
'2021-01-25'
>>> 

请记住,strptime() 使用屏蔽字符格式从 string 匹配日期创建了一个 datetime 对象。在 datetime 对象中获得正确的掩码和正确的表示后,您可以使用 strftime().

将其转换为所需的格式

有关详细信息,请查看 strftime() and strptime() Format Codes

你可以使用

date_like_you_dont_want = "Jan 2,2021".lower()

day = date_like_you_dont_want[4:6]

if not ',' in day:
    year = date_like_you_dont_want[7:]
else:
    day=date_like_you_dont_want[4]
    year=date_like_you_dont_want[6:]

month=date_like_you_dont_want[:3]
if month =='jan':
    month = '01'
elif month =='fev':
    month = '02'
elif month =='mar':
    month = '03'
elif month =='may':
    month = '04'
elif month =='apr':
    month = '05'
elif month =='jun':
    month = '06'
elif month =='jul':
    month = '07'
elif month =='aug':
    month = '08'
elif month =='sep':
    month = '09'
elif month =='oct':
    month = '10'
elif month =='mov':
    month = '11'
elif month =='dez':
    month = '12'

print(year+'-'+day+'-'+month)