将字符串转换为日期缺少某些值

2024-04-20 13:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够在python中将字符串转换为日期格式。但有些日期和月份被指定为00。你知道吗

date = ['00-00-2001', '10-01-2014']

当我尝试时:

datetime.strptime(date[1], '%d-%m-%Y'),当然可以, 但是做datetime.strptime(date[0], '%d-%m-%Y'),我得到了以下错误。你知道吗

time data '00-00-2001' does not match format '%d-%m-%Y'


Tags: 字符串formatdatadatetimedatetime格式match
2条回答

根据Python Docs

%d Day of the month as a zero-padded decimal number. 01, 02, ..., 31

%m Month as a zero-padded decimal number. 01, 02, ..., 12

它们都不接受00作为有效字符串。你知道吗

另请参阅我在https://stackoverflow.com/a/38801552/1005215的回答,它解释了如何通过传递默认参数来使用来自dateutilparser。你知道吗

执行:

corrected_date = []
for d in dates:
    components = d.split('-')
    components = [str(c).zfill(2) if(int(c) > 0) else str(int(c) + 1).zfill(2) for c in components]
    corrected_date.extend(['-'.join(components)])

现在在corrected_date上试试你的strftime。你知道吗

相关问题 更多 >