python .rstrip删除一个额外的字符

时间:2011-06-10 20:53:35

标签: python

我尝试从日期删除秒数:

>>> import datetime
>>> test1 = datetime.datetime(2011, 6, 10, 0, 0)
>>> test1
datetime.datetime(2011, 6, 10, 0, 0)
>>> str(test1)
'2011-06-10 00:00:00'
>>> str(test1).rstrip('00:00:00')
'2011-06-10 '
>>> str(test1).rstrip(' 00:00:00')
'2011-06-1'

为什么删除'10'末尾的0?

2 个答案:

答案 0 :(得分:11)

str.rstrip()不会删除确切的字符串 - 它会删除字符串中出现的所有字符。由于您知道要删除的字符串的长度,因此您只需使用

即可
str(test1)[:-9]

甚至更好

test1.date().isoformat()

答案 1 :(得分:7)

rstrip接受一组(尽管参数可以是任何可迭代的,例如在您的示例中为str)被删除的字符,而不是单个字符串。

顺便说一下,datetime.datetime的字符串表示不是固定的,你不能依赖它。相反,请在isoformatdate上使用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'
相关问题