使用 python 的日期格式
Date formatting using python
要获取日期,我使用此块:
currentDate = date.today()
today = currentDate.strftime('%m/%d/%Y')
它 return 给我这个格式 12/22/2014 或 01/02/2015
然后我必须与文件中的字符串进行比较(注意:我无法更改字符串)12/22/2014 或 1/2/2015 我使用:
if l[0] == today:
第二种情况显然失败了。
我的问题:我如何更改 strftime() 以便 return 只有一个字符作为月份和日期的前导零?
参考documentation,好像没有这个字符序列。但是,您可以按如下方式更正结果:
today = currentDate.strftime('%m/%d/%Y').replace("/0", "/")
if today[0] == '0':
today = today[1:]
这将消除任何前导 0
,只要值用正斜杠分隔即可。
只比较日期时间对象:
from datetime import datetime, date
currentDate = date.today()
file_dt = "1/3/2015"
dt2 = datetime.strptime(file_dt,"%m/%d/%Y")
print(dt2.date() == currentDate)
today = currentDate.strftime('%-m/%-d/%Y')
警告,非标准,因此无法在某些平台上工作(查看 strftime(3) 文档,第 "Glibc notes" 节)。无论如何,我同意其他答案,最好比较日期时间对象
要获取日期,我使用此块:
currentDate = date.today()
today = currentDate.strftime('%m/%d/%Y')
它 return 给我这个格式 12/22/2014 或 01/02/2015 然后我必须与文件中的字符串进行比较(注意:我无法更改字符串)12/22/2014 或 1/2/2015 我使用:
if l[0] == today:
第二种情况显然失败了。 我的问题:我如何更改 strftime() 以便 return 只有一个字符作为月份和日期的前导零?
参考documentation,好像没有这个字符序列。但是,您可以按如下方式更正结果:
today = currentDate.strftime('%m/%d/%Y').replace("/0", "/")
if today[0] == '0':
today = today[1:]
这将消除任何前导 0
,只要值用正斜杠分隔即可。
只比较日期时间对象:
from datetime import datetime, date
currentDate = date.today()
file_dt = "1/3/2015"
dt2 = datetime.strptime(file_dt,"%m/%d/%Y")
print(dt2.date() == currentDate)
today = currentDate.strftime('%-m/%-d/%Y')
警告,非标准,因此无法在某些平台上工作(查看 strftime(3) 文档,第 "Glibc notes" 节)。无论如何,我同意其他答案,最好比较日期时间对象