Home > Enterprise >  Is there a more efficient to replace the elements in a string based on their position?
Is there a more efficient to replace the elements in a string based on their position?

Time:01-18

I have the following string '2022-01-03 20:04:22' and I would like to change the last two elements to '00' so it looks like this '2022-01-03 20:04:00'.

I have worked out the following method:

s = '2022-01-03 20:04:22'
print(s)

n = len(s) - 2
print(n)

r = '00'
print(r)

s = s[0:n]   r
print(s)


Output:
2022-01-03 20:04:22
17
00
2022-01-03 20:04:00

It gets the job done but I feel their should be a better way.

For example, I tried this first:

s = '2022-01-03 20:04:22'
s = s.replace(s[-2:], '00')

But I end up with this: 2000-01-03 20:04:00 where the '22' in the year is also changes to '00'.

I understand now that the s[-2:] extracts the value from that index which is '22' and then it finds this value twice in the string (in the year 2022 and in the seconds part of the datetime) and replaces them with '00'.

Thus far, I haven't found a solution to replace the characters that are at a specific position in the string.

CodePudding user response:

How about string slicing:

s = s[:-2]   '00'

Output:

'2022-01-03 20:04:00'

CodePudding user response:

Since you're working with dates and times, there is a replace() method that can help you in this case. To round down to the minute, as in your example, you could do:

from dateutil import parser
foo = parser.parse("2022-01-03 20:04:22")
foo = foo.replace(microsecond=0, second=0)

Printing that out back into a string:

foo.strftime("%Y-%m-%d %H:%M:%S")

Would give you:

'2022-01-03 20:04:00'

CodePudding user response:

I can see that the given string is of a datetime type. You can use the code below to get the desired result.

from datetime import datetime

s = '2022-01-03 20:04:22'

date_object = datetime.strftime(datetime.fromisoformat(s),"%Y-%m-%d %H:%M:00")

print(date_object)
  •  Tags:  
  • Related