比较 Python 中的两个日期字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20365854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:17:18  来源:igfitidea点击:

Comparing two date strings in Python

pythondatedatetime

提问by Sid K.

Let's say I have a string: "10/12/13" and "10/15/13", how can I convert them into date objects so that I can compare the dates? For example to see which date is before or after.

假设我有一个字符串:“10/12/13”和“10/15/13”,如何将它们转换为日期对象以便比较日期?例如查看哪个日期早于或晚于。

回答by gongzhitaao

If you like to use the dateutiland its parser:

如果您喜欢使用dateutil及其解析器:

from dateutil.parser import parse

date1 = parse('10/12/13')
date2 = parse('10/15/13')

print date1 - date2
print date2 > date2

回答by aIKid

Here's one solution using datetime.datetime.strptime:

这是使用的一种解决方案datetime.datetime.strptime

>>> date1 = datetime.datetime.strptime('10/12/13', '%m/%d/%y')
>>> date2 = datetime.datetime.strptime('10/15/13', '%m/%d/%y')
>>> date1 < date2
True
>>> date1 > date2
False

回答by Paul Draper

Use datetime.datetime.strptime.

使用datetime.datetime.strptime.

from datetime import datetime

a = datetime.strptime('10/12/13', '%m/%d/%y')
b = datetime.strptime('10/15/13', '%m/%d/%y')

print 'a' if a > b else 'b' if b > a else 'tie'

回答by Paul Draper

Use datetime.datetime.strptime:

使用datetime.datetime.strptime

>>> from datetime import datetime as dt
>>> a = dt.strptime("10/12/13", "%m/%d/%y")
>>> b = dt.strptime("10/15/13", "%m/%d/%y")
>>> a > b
False
>>> a < b
True
>>>