Python.rstrip removes one extra character

I am trying to remove seconds from a date:

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

Why is 0 at the end of '10' deleted?

+6
source share
2 answers

str.rstrip() does not delete the exact string - it removes all the characters that occur in the string. Since you know the length of the string to delete, you can simply use

 str(test1)[:-9] 

or even better

 test1.date().isoformat() 
+7
source

rstrip accepts the set (although the argument can be any iterable, for example str in your example) of characters to delete, rather than a single line.

And by the way, the string representation of datetime.datetime not fixed, you cannot rely on it. Instead, use isoformat on 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' 
+7
source

Source: https://habr.com/ru/post/890256/


All Articles