比较python中的日期字符串 [英] Comparing date strings in python

查看:78
本文介绍了比较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

我试图在不使用库的情况下比较python3中的日期,并且看来工作正常.这是真的吗?python真的了解这些字符串是日期,并根据日期格式对它们进行比较吗?还是幕后发生了其他事情?

I tried to compare dates in python3 without using a library and it seems to be working correctly. 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!

这是一个反例:

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

作为处理日期的正确方法,您应该使用 datetime 模块,其中有很多用于处理日期对象的工具.

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.datetime.strptime ,然后您就可以使用基本的算术运算来比较您的日期对象,因为该对象已被该模块支持.

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.

这篇关于比较python中的日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆