且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何验证字符串为正确的日期格式

更新时间:2023-11-07 18:56:34

您的主要问题实际上是%m 应该为%M 。小写的 m 是月份,而不是分钟。 %p 将解析'am''pm' 。您可能还想将%H 更改为%I ,因为am / pm的存在意味着需要12小时制大于24:

Your main issue is actually that %m should be %M. Lowercase m is the month, not the minute. %p will parse 'am' and 'pm'. You may also want to change %H to %I since the presence of am/pm implies a 12 hour clock rather than 24:

datestring = 'Feb 22 2017, 1:27:42pm'
datetime.strptime(datestring, '%b %d %Y, %I:%M:%S%p')

结果在 datetime 对象中,该对象可以用我的语言环境/平台表示为 2017-02-22 13:27:42 默认值。

Results in a datetime object that can be represented as 2017-02-22 13:27:42 with my locale/platform defaults.