Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python .rstrip removes one additional character

Tags:

python

I try to remove seconds from 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 0 at end of '10' is removed?

like image 370
zzzz Avatar asked Jun 10 '11 20:06

zzzz


People also ask

How do you remove an extra character from a string in Python?

Python Remove Character from String using translate() Python string translate() function replace each character in the string using the given translation table. We have to specify the Unicode code point for the character and 'None' as a replacement to remove it from the result string.

How do you exclude a character in Python?

Using translate(): translate() is another method that can be used to remove a character from a string in Python. translate() returns a string after removing the values passed in the table. Also, remember that to remove a character from a string using translate() you have to replace it with None and not "" .

How do I remove a trailing character in Python?

Python String rstrip() Method The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.


2 Answers

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()
like image 186
Sven Marnach Avatar answered Sep 24 '22 03:09

Sven Marnach


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'
like image 33
phihag Avatar answered Sep 24 '22 03:09

phihag