from datetime import datetime
datetime.strptime('%b%d %I:%M%p', 'AUG21 3:26PM')
results with
1900-08-21 15:26:00
如何以Pythonic的方式编写代码,使得当没有提供年份时,默认使用当前年份(2013)?我已经检查了strftime函数,没有选项可以更改默认设置。也许其他第三方库可以做到这点?谢谢。from datetime import datetime
datetime.strptime('%b%d %I:%M%p', 'AUG21 3:26PM')
results with
1900-08-21 15:26:00
如何以Pythonic的方式编写代码,使得当没有提供年份时,默认使用当前年份(2013)?我已经检查了strftime函数,没有选项可以更改默认设置。也许其他第三方库可以做到这点?谢谢。请按照您已经做的那样解析日期,然后:
date= date.replace(2013)
使用您正在使用的模块之一,这是最简单的解决方案之一。
更好地考虑一下,您可能会在明年2月29日遇到问题。
input= 'Aug21 3:26PM'
output= datetime.datetime.strptime('2013 '+ input ,'%Y %b%d %I:%M%p')
datetime
源代码并重新编译。这是一个旧问题,我不知道其他解决方案。我能想到的唯一替代方案(因为修改库模块绝对太过激烈,我简直不敢相信我刚刚推荐了它 :-))就是检查格式(以及日期)是否带有年份。如果没有,那么你就“黑客”它们。否则,你就让它们保持原样。 - Mario Rossi您可以查找今天的日期以替换年份进行动态替换。
datetime.strptime('%b%d %I:%M%p', 'AUG21 3:26PM').replace(year=datetime.today().year)