2

What is the correct way to get milliseconds expressed as a float, assuming you have subtracted a previous time (in the format 20150401 00:04:45.809) from a more present time (in the same format obviously) to get :

for k in xrange(2,len(df)):

    now  = str(df['datetime'][k])
    then = str(df['datetime'][k-1])

    dta  = datetime.datetime.strptime(now, "%Y%m%d %H:%M:%S.%f")
    dtb  = datetime.datetime.strptime(then, "%Y%m%d %H:%M:%S.%f")

    print dta - dtb

Example output:

0:00:01.767000
0:00:00.186000
0:00:00
0:00:00.062000
0:00:02.009000
0:00:01.406000
0:00:00.004000
0:00:00.904000
0:00:00.462000
0:00:08.602000

So for example, taking the last line, how do I get 8602.0ms?

Tom
  • 918
  • 6
  • 19
ajsp
  • 2,512
  • 22
  • 34
  • possible duplidate http://stackoverflow.com/questions/6999726/how-can-i-convert-a-datetime-object-to-milliseconds-since-epoch-unix-time-in-p – Nikos M. May 09 '15 at 19:56
  • Correct, it more or less is. Just use ((dta-dtb).total_seconds())*1000. Thanks. – ajsp May 09 '15 at 20:15
  • what is `df['datetime'][k]`? why do you call `str()` only to call `.strptime()` immediately? The conversions seem unnecessary. If input time is the local time then beware of DST, see how to get the correct difference in [Find if 24 hrs have passed between datetimes - Python](http://stackoverflow.com/a/26313848/4279). – jfs May 09 '15 at 22:06
  • @ J.F. Sebastian df['datetime'][k] is a pandas dataframe, (the str() is unnecessary, long story). The code won't need to worry about DST or anything subtle; it's more of an intraday thing. Thanks. – ajsp May 09 '15 at 22:59
  • Are you trying to implement [`pandas.DataFrame.diff()`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.diff.html)? – jfs May 10 '15 at 22:13
  • @J.F. Sebastian It's probably workable, but better the devil you know; been down a few blind alleys with pandas now, so i've become weary of delving into the documentation for anything too exotic, or in this case, too simple. I will probably fully commit to pandas eventually...as trying to cherry-pick from numpy, scipy and pandas can become a bit of a headache in itself. – ajsp May 11 '15 at 12:23
  • @ajsp: I sympathise: the api provided by numpy, scipy, and pandas might seem overwhelming. If you know the core conventions and the corresponding underlying math then it is easy to pick up new unfamiliar functions. You should avoid reimplementing adjacent difference algorithms `d[i] = a[i+1]-a[i]` if possible (test and see whether the stock `diff` works for you). You are right [the `diff()` implementation](https://github.com/pydata/pandas/blob/eafd22d961934a7b3cc72607ef4512a18b419085/pandas/core/common.py#L928) is simple but it is not trivial -- enough places to break. – jfs May 11 '15 at 12:46

0 Answers0