简体   繁体   English

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

[英]Comparing two date strings in Python

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?假设我有一个字符串:“10/12/13”和“10/15/13”,如何将它们转换为日期对象以便比较日期? For example to see which date is before or after.例如查看哪个日期早于或晚于。

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
>>>

If you like to use the dateutil and its parser:如果您喜欢使用dateutil及其解析器:

from dateutil.parser import parse

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

print date1 - date2
print date2 > date2

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

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'

I know this post is 7 years old, but wanted to say that you can compare two date strings without converting them to dates我知道这篇文章已经有 7 年的历史了,但我想说的是,您可以比较两个日期字符串而无需将它们转换为日期

>>> "10/12/13" > "10/15/13"
False
>>> "10/12/13" < "10/15/13"
True
>>> "10/12/13" == "10/15/13"
False

If there is anything wrong with this approach I would love for someone to tell me.如果这种方法有什么问题,我希望有人告诉我。

import datetime

d1="10/12/13"
d2="10/15/13"
date = d1.split('/')
d1=datetime.datetime(int(date[2]),int(date[1]),int(date[0])) 
date = d2.split('/')
d2=datetime.datetime(int(date[2]),int(date[1]),int(date[0]))
if d1 > d2 :
    ## Code
today = datetime.datetime.today()
if d1 > today :
    ## code

The simplest way to accomplish this is using Pandas最简单的方法是使用 Pandas

import pandas as pd
d1=pd.to_datetime("10/12/13")
d2=pd.to_datetime("10/12/15")

d1>d2

>>False

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

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