Python:是否传递了带有字符串的日期逻辑
在一个迭代了许多日期的大型程序中,我试图只处理通过(或在)一个Python:是否传递了带有字符串的日期逻辑,python,date,Python,Date,在一个迭代了许多日期的大型程序中,我试图只处理通过(或在)一个截止日期的日期,其中日期>=截止日期。这在99%的情况下都非常有效,但是请查看以下内容: >>> print cutoff_date, type(cutoff_date) 2015-2-19 <type 'str'> >>> a = '2015-3-20' >>> a >= cutoff_date True >>> b = '2015-1-2'
截止日期
的日期,其中日期>=截止日期
。这在99%的情况下都非常有效,但是请查看以下内容:
>>> print cutoff_date, type(cutoff_date)
2015-2-19 <type 'str'>
>>> a = '2015-3-20'
>>> a >= cutoff_date
True
>>> b = '2015-1-2'
>>> b >= cutoff_date
False
>>> c = '2015-2-9'
>>> c >= cutoff_date
True # I need this to be False ...
>>> d = '2015-2-09'
>>> d >= cutoff_date
False # ... just like this
>>>
打印截止日期,类型(截止日期)
2015-2-19
>>>a=‘2015-3-20’
>>>a>=截止日期
真的
>>>b=‘2015-1-2’
>>>b>=截止日期
假的
>>>c=‘2015-2-9’
>>>c>=截止日期
真的#我需要这是假的。。。
>>>d=‘2015-2-09’
>>>d>=截止日期
假。。。就这样
>>>
我知道我可以设置一个函数,如果日期的日期是一位数字,则在其前面添加一个0
。然而,我担心这会把我的代码搞砸。因此,在开始之前,我想知道是否有更简单的方法来解决这个问题?使用模块处理日期,并解析表示日期的字符串
>>> import datetime
>>> cutoff = datetime.datetime.strptime('2015-2-19', '%Y-%m-%d')
>>> a = datetime.datetime.strptime('2015-3-20', '%Y-%m-%d')
>>> b = datetime.datetime.strptime('2015-1-2', '%Y-%m-%d')
>>> c = datetime.datetime.strptime('2015-2-9', '%Y-%m-%d')
>>> d = datetime.datetime.strptime('2015-2-09', '%Y-%m-%d')
>>> a>=cutoff
True
>>> b>=cutoff
False
>>> c>=cutoff
False
>>> d>=cutoff
False
要正确比较日期,必须将它们设置为
DateTime
或Date
对象。为此,请使用datetime.datetime.strtime()
:
这是因为你不是在处理日期,而是在处理字符串。默认情况下,这些数据按字母顺序处理。使用
datetime.datetime
或datetime.date
解析日期,您就可以开始了。类似于datetime.datetime.strtime(a,“%Y-%m-%d”)
的内容对于您的目的可能已经足够了。
from datetime import datetime
d = datetime.strptime('2015-09-01', '%Y-%m-%d')
cut_off = datetime(2015, 9, 1)
if d >= cutoff:
print('True')
>>> from datetime import datetime
>>> dateify = lambda ds: datetime.strptime(ds, '%Y-%m-%d')
>>> dateify('2015-2-19') > dateify('2015-2-18')
True
>>> dateify('2015-2-19') > dateify('2015-2-20')
False