0

I have a variable which has time in H:M:S format like below

 h2='00:00:01'

i want to change the H part in it to 10 so that it becomes

h2='10:00:01'

I tried the below code, but it dint work

h2.split(':')[0]=10
print(h2)

Output:

00:00:01

Expected Output:

10:00:01

How can i change the value of part of a variable?

2
  • 1
    take a look at the datetime module if you are going to be working with dates extensively Commented Jun 11, 2018 at 11:00
  • 1
    a) strings can not be modified in Python, you have to construct a new one. b) for any serious date or time calculation use a proper library. datetime is built-in, but there are others like for example arrow as well. Commented Jun 11, 2018 at 11:38

2 Answers 2

2

You are pretty close.

Try:

h2='00:00:01'
h2 = h2.split(":")
h2[0] = '10'
print( ":".join(h2) )

If you can use the datetime module

import datetime
h2='00:00:01'
time = datetime.datetime.strptime(h2, "%H:%M:%S")
print( time.replace(hour=10).strftime("%H:%M:%S") )

Output:

10:00:01
Sign up to request clarification or add additional context in comments.

Comments

0

You mean how do you edit a string in-place? You can't, python string are immutable. You need to make a new string with a new value. What you're doing is the following

h2.split(':')  # makes a new list ['00', '00', '01']
h2.split(':')[0] = 10  # mutate said lest so it now equals ['10', '00', '01']
# then you just send that list you made into the void, you never assign it to anything

Instead you need to create a new object

h2 = '00:00:01'
h2_split = h2.split(':')
h2_split[0] = '10'
h3 = ':'.join(h2_split)
h2 = h3  # optionally reassign your original variable this new value

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.