使用python格式化日期

sus*_*sja 5 python datetime

要获取日期,我使用以下代码块:

currentDate = date.today()
today = currentDate.strftime('%m/%d/%Y')
Run Code Online (Sandbox Code Playgroud)

它以这种格式返回我12/22/2014或01/02/2015然后我必须比较文件中的字符串(注意:我不能更改字符串)12/22/2014或1/2/2015,我使用:

if l[0] == today:
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,它显然失败了。我的问题:如何更改strftime()以使其在日和日之前仅返回零个字符,而其前一个为零?

OMG*_*chy 3

参考文档,似乎没有相应的字符序列。但是,您可以按如下方式更正结果:

today = currentDate.strftime('%m/%d/%Y').replace("/0", "/")
if today[0] == '0':
    today = today[1:]
Run Code Online (Sandbox Code Playgroud)

0只要值用正斜杠分隔,这就会消除任何前导s。