1

How can i convert this timestamp value to an integer representing seconds-since-the-epoch in python

 2016-08-06T06:07:36.349Z

This is the timestamp value i received in elastic search query.

I tried searching but the timestamp format was different from this and this didn't helped neither any other

Community
  • 1
  • 1
prashantitis
  • 1,797
  • 3
  • 23
  • 52
  • Possible duplicate of [How to parse an ISO 8601-formatted date in Python?](http://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date-in-python) – Lukas Graf Aug 07 '16 at 20:17

1 Answers1

6

You can use python inbuilt datetime package and its strptime method to convert string into datetime object.

from datetime import datetime
datetime.strptime("2016-08-06T06:07:36.349Z","%Y-%m-%dT%H:%M:%S.%fZ")

after that you should get epoch datetime object which you can get by

epoch = datetime.utcfromtimestamp(0)

your final seconds can be derived from this method

def unix_time_millis(datetime):
    return (datetime - epoch).total_seconds() * 1000.0

so your complete code looks like

from datetime import datetime

epoch = datetime.utcfromtimestamp(0)

def unix_time_millis(datetime):
    return (datetime - epoch).total_seconds() * 1000.0

current_date = datetime.strptime("2016-08-06T06:07:36.349Z","%Y-%m-%dT%H:%M:%S.%fZ")
print unix_time_millis(current_date)

This answer is inspired from this answer https://stackoverflow.com/a/11111177/4453633

Community
  • 1
  • 1
Sumit
  • 2,190
  • 23
  • 31
  • Thanks @Sumit Kumar – prashantitis Aug 07 '16 at 20:39
  • @sumit how can we convert the timestamp into general timestamp – ak3191 Aug 30 '18 at 17:38
  • @ak3191 I didn't understand your question, what is a timestamp vs. general timestamp? Could you please elaborate – Sumit Aug 31 '18 at 10:19
  • I'm not sure whether this is an ES version discrepancy, but the date-time strings returned on `v2.4.6` don't have the trailing "Z". Also, in case `dt.microsecond == 0`, `str(dt)` will omit the `.000000` suffix, whereas `dt.strftime(fmt + ".%f")` will print it. So, depending on how the strings were generated in the first place, `strptime()` may raise a ValueError for nil microseconds. Is there an official ISO name for the date strings returned by ES? Also, your `datetime` local shadows the imported symbol. – init_js Dec 17 '18 at 08:53