简体   繁体   English

比较python中的日期字符串

[英]Comparing date strings in python

>> a ='2009-05-10'
>>> b ='2009-06-10'
>>> a > b
False
>>> a < b
True
>>> type(a)
<class 'str'>
>>> c = '2009-06-09'
>>> b < c
False
>>> b > c
True
>>> c ='2008-07'
>>> b > c
True
>>> a > c
True

I tried to compare dates in python3 without using a library and it seems to be working correctly. 我试图在不使用库的情况下比较python3中的日期,它似乎正常工作。 Is this the real case? 这是真的吗? Does python really understands that these strings are dates and comparing them according to date format or is something else is going on behind the scenes ? python是否真的理解这些字符串是日期并根据日期格式进行比较,还是在幕后进行其他事情?

No, there is no spacial thing behind this behavior. 不,这种行为背后没有空间的东西。 As a matter of fact, Python compares the strings lexicographicaly and in this case it works, but it's not the right way to go, because it can also accepts the wrong dates! 事实上,Python比较字符串lexicographicaly,在这种情况下它可以工作,但它不是正确的方法,因为它也可以接受错误的日期!

Here is a Counterexample : 这是一个反例

>>> a ='2009-33-10'
>>> b ='2009-11-1'
>>> a>b
True

As a proper way for dealing with dates you should use datetime module which has a lot of tools for working with date objects. 作为处理日期的正确方法,您应该使用datetime模块,该模块具有许多用于处理日期对象的工具。

You can convert your strings to date object with datetime.datetime.strptime and then you can use basic arithmetic operation to compare your date objects, as they've been supported already by this module. 您可以使用datetime.datetime.strptime将字符串转换为日期对象,然后您可以使用基本算术运算来比较日期对象,因为此模块已经支持它们。

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM