Cellular777
Cellular777

Reputation: 35

Calculate elapsed time

I have a text file that always looks like this:

977-183 BCA-0055 2014-02-19 10:08:13.61
977-001 BCA-0058 2014-02-19 10:29:08.18
977-013 BCA-0064 2014-02-19 10:28:35.73
977-129 BCA-0079 2014-02-19 10:15:45.24

These are generators. My goal is to add an additional column showing the total hours they have been running until now, which is when the I run the script. I am brand new to python and am stuck. I have figured out how to make a datetime object? for the now time. I had hoped to use this in my calculations (timedelta?) but have not been able to create a datetime for the times in the text file to move on. I have tried some things and read quite a bit but no luck, here is code showing my latest attempt:

import datetime
import time

i = datetime.datetime.now()
print i

# this is what the raw data looks like
# 977-183 BCA-0055 2014-02-19 10:08:13.61

raw0 = open("genParse.txt", "r") # text file containing date and time
fin0 = open("elapsed_time.txt", "w") # will contain elapsed times

for line in raw0:
    if '977-' in line:
       line = line.split() 
       date = line[2]
       time = line[3]
             # create datetime object for use in elapsed time calculations
             #tnew = datetime.datetime(date[0:4], date[5:7], date[8:10])
             print date[0:4], date[5:7], date[8:10]

Upvotes: 1

Views: 2350

Answers (2)

Drewness
Drewness

Reputation: 5072

If you want to get the difference between the entry and when the script is executed:

from datetime import datetime

raw0 = open("genParse.txt", "r") # text file containing date and time
fin0 = open("elapsed_time.txt", "w") # will contain elapsed times

for line in raw0:
    if '977-' in line:
        line = line.split() 
        dts = '%s %s' % (line[2], line[3])
        now = datatime.now()
        fmt = '%Y-%m-%d %H:%M:%S.%f'
        time_diff = datetime.strptime(now, FMT) - datetime.strptime(dts, FMT)

You can obviously do whatever you want with time_diff, which is a timedelta object. Print, to file, etc. This is just expanding on the code you have already written. Like always with Python, there are many ways to accomplish the same goal.

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121266

Use datetime.datetime.strptime() to parse your strings to datetime.datetime() objects:

dt = datetime.datetime.strptime(date + ' ' + time, '%Y-%m-%d %H:%M:%S.%f')

Now you can calculate the time elapsed:

elapsed = now - dt

which is a timedelta object.

Demo:

>>> import datetime
>>> now = datetime.datetime.now()
>>> date = '2014-02-19'
>>> time = '10:08:13.61'
>>> dt = datetime.datetime.strptime(date + ' ' + time, '%Y-%m-%d %H:%M:%S.%f')
>>> dt
datetime.datetime(2014, 2, 19, 10, 8, 13, 610000)
>>> now - dt
datetime.timedelta(6, 30419, 490913)

The resulting timedelta object here has a value of 6 days, 30419 seconds and 490913 microseconds. How you format that to a string is up to you.

Upvotes: 3

Related Questions