Reputation: 189
I'm currently using this to obtain latency:
def time_deltas(infile):
entries = (line.split() for line in open(INFILE, "r"))
ts = {}
for e in entries:
if " ".join(e[2:5]) == "TMsg out: [O]":
ts [e[8]] = e[0]
elif " ".join(e[2:5]) == "TMsg in: [A]":
in_ts, ref_id = e[0], e[7]
out_ts = ts.pop(ref_id, None)
yield (float(out_ts),ref_id[1:-1],(float(in_ts)*1000 - float(out_ts)*1000))
INFILE = 'C:/Users/klee/Documents/test.txt'
print list (time_deltas(INFILE))
I would like to convert the float(out_ts) to Unix epoch seconds.
I've tried the following, but have failed miserably:
int(time.mktime(time.strptime('(out_ts)', '%H%M%S.%f'))) - time.timezone
AND
t = time.strptime(float(out_ts), "%H%M%S.%f")
print "Epoch Seconds:", time.mktime(t.timetuple())
AND
d = datetime.strptime("out_ts", "%H%M%S.%f")
time.mktime(d.timetuple())
AND
pattern = "%H%M%S.%f"
epoch = int(time.mktime(time.strptime(out_ts, pattern))
print 'epoch'
Here's an example of a time I want to convert:
82128.668173
I'm quite new to Python and any help would be appreciated!!
Upvotes: 2
Views: 2424
Reputation: 208545
The strptime()
functions convert strings to times or dates, so if out_ts
is a float you will first need to convert it to a string, for example:
>>> out_ts = 82128.668173
>>> time.strptime(str(out_ts), '%H%M%S.%f')
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=21, tm_sec=28, tm_wday=0, tm_yday=1, tm_isdst=-1)
>>> datetime.strptime(str(out_ts), '%H%M%S.%f')
datetime.datetime(1900, 1, 1, 8, 21, 28, 668173)
However, you will not be able to convert these dates to an epoch time because epoch time is seconds elapsed since January 1, 1970, and because out_ts
only contains hour/minute/second information, you are getting dates/times in 1900.
You will need to clarify what date you want the epoch time to be calculated for. The time for this example is 8:21:28, but do you want that for 1/1/1970, today's date, or some other date?
A simple way to add an arbitrary date to your time would be to use a datetime.timedelta
object which represents your time, and then add it to a datetime
object for the date you want, for example:
>>> from datetime import datetime, timedelta
>>> out_ts = 82128.668173
>>> dt = datetime.strptime(str(out_ts), '%H%M%S.%f')
>>> td = timedelta(hours=dt.hour, minutes=dt.minute, seconds=dt.second)
>>> td
datetime.timedelta(0, 30088)
>>> date = datetime(2012, 2, 13)
>>> full_time = date + td
>>> full_time
datetime.datetime(2012, 2, 13, 8, 21, 28)
>>> epoch = time.mktime(full_time.timetuple())
>>> epoch
1329150088.0
Upvotes: 1