Cotton candy
Cotton candy

Reputation: 21

Adding time to an existing file in python

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

Upvotes: 1

Views: 197

Answers (3)

jspurim
jspurim

Reputation: 955

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();

Upvotes: 1

LetMeSOThat4U
LetMeSOThat4U

Reputation: 6796

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'

Upvotes: 1

dano
dano

Reputation: 94961

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'

Upvotes: 2

Related Questions