1

I want to update an existing file.txt in Python, which has two columns, one for days, and one for time, so that it will sum up a new time in another column on the same file.

Sunday      07:00
Monday      07:35
Tuesday     05:35
Wednesday   06:45
Thursday    08:40

For example, adding 30 minutes:

Sunday      07:00   07:30
Monday      07:35   08:05
Tuesday     05:35   06:05
Wednesday   06:45   07:15
Thursday    08:40   09:10
2
  • what does this have to do with the django tag? :) Commented May 16, 2014 at 15:07
  • Could you add some code you have already tried? Commented May 16, 2014 at 15:20

3 Answers 3

2

The datetime module is very helpful for this. It lets you create time objects and timedelta objects which can be added together by simply using the + operator. So, to add thirty minutes to 08:30:25:

>>> from datetime import datetime, timedelta
>>> d = datetime.strptime("08:30:25", "%I:%M:%S") + timedelta(minutes=30)
>>> d.strftime("%I:%M:%S")
'09:00:25'
Sign up to request clarification or add additional context in comments.

Comments

1
In [139]: d='Sunday      07:00'

In [140]: b=d.split()

In [141]: b
Out[141]: ['Sunday', '07:00']

In [142]: (datetime.datetime.strptime(b[1], '%H:%M') + datetime.timedelta(minutes=30)).strftime('%H:%M')
Out[142]: '07:30'

2 Comments

outfile=open('file.txt','w')<br> <br> dict={}<br> <br> for line in file('file.txt','r'):<br> (key, val) = line.split() <br> dict[key] = val <br> print dict<br> <br> <br> obj=Salestracker()<br> for i in dict.keys():<br> outfile.write(i)<br> val =dict.get(i)<br> outfile.write(' ')<br> outfile.write(val)<br> outfile.write(' ')<br> for i in range(1,5): <br> q=int(raw_input("enter the sale after each 1 hr"))<br> val=obj.updateSales(val,q)<br> outfile.write(val)<br> outfile.write(' ')<br> outfile.write('\n')
@Cottoncandy Edit your original question to include that code. Its unreadable as the comment.
1
from datetime import datetime, timedelta

f=open("testcase","r") #open the file

pairs = [l.split() for l in f.readlines()] #get [day,time] pairs

f.close()

#this long line creates a list of [day,time1,time2] using list comprehensions
#you can change it a bit to change the output format.
data = ["%s%s%s\n" % (p[0].ljust(12),p[1].ljust(8), 
    (datetime.strptime(p[1],"%H:%M") + timedelta(minutes=30)).strftime("%H:%M")) 
    for p in pairs]

#reopen the file for writing and store the new data.
f = open("testcase","w")
f.writelines(data)
f.close();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.