python .rstrip removes one additional character

前端 未结 2 465
夕颜
夕颜 2020-12-03 18:38

I try to remove seconds from date:

>>> import datetime
>>> test1 = datetime.datetime(2011, 6, 10, 0, 0)
>>> test1
datetime.datetim         


        
相关标签:
2条回答
  • 2020-12-03 18:45

    str.rstrip() doesn't remove an exact string -- it removes all characters that occur in the string. Since you know the length of the string to remove, you can simply use

    str(test1)[:-9]
    

    or even better

    test1.date().isoformat()
    
    0 讨论(0)
  • 2020-12-03 18:58

    rstrip takes a set (although the argument can be any iterable, like str in your example) of characters that are removed, not a single string.

    And by the way, the string representation of datetime.datetime is not fixed, you can't rely on it. Instead, use isoformat on the date or strftime:

    >>> import datetime
    >>> test1 = datetime.datetime(2011, 6, 10, 0, 0)
    >>> test1.date().isoformat()
    '2011-06-10'
    >>> test1.strftime('%Y-%m-%d')
    '2011-06-10'
    
    0 讨论(0)
提交回复
热议问题