Comparing two date strings in Python

前端 未结 6 979
庸人自扰
庸人自扰 2020-11-29 07:56

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

相关标签:
6条回答
  • 2020-11-29 08:30

    Use 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'
    
    0 讨论(0)
  • 2020-11-29 08:34

    If you like to use the dateutil and its parser:

    from dateutil.parser import parse
    
    date1 = parse('10/12/13')
    date2 = parse('10/15/13')
    
    print date1 - date2
    print date2 > date2
    
    0 讨论(0)
  • 2020-11-29 08:37

    Use 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
    >>>
    
    0 讨论(0)
  • 2020-11-29 08:43

    Here's one solution using 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
    
    0 讨论(0)
  • 2020-11-29 08:45

    The simplest way to accomplish this is using Pandas

    import pandas as pd
    d1=pd.to_datetime("10/12/13")
    d2=pd.to_datetime("10/12/15")
    
    d1>d2
    
    >>False
    
    0 讨论(0)
  • 2020-11-29 08:50
    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
    

    0 讨论(0)
提交回复
热议问题