0

I have data frame which has a column full of date-time of format yyyy-mm-ddTHH:MM:SSS.000Z

For example, 2019-06-17T19:17:45.000Z. I want to convert this to long type (unix epoch time) in python.

How to do that?

Thanks!

(How do I parse an ISO 8601-formatted date? This question is abut parsing the string. I want to do a conversion and hence it is different)

yahooo
  • 103
  • 9

2 Answers2

1

Use module time:

import calendar
import time
calendar.timegm(time.strptime('2019-06-17T19:17:45.000Z', '%Y-%m-%dT%H:%M:%S.%fZ'))

Output: 1560799065

Rorepio
  • 332
  • 1
  • 4
  • 16
  • You should also be able to use %z in the format string, `'%Y-%m-%dT%H:%M:%S.%f%z'`, to parse the Z character. However, to make use of the result, you'll have to use `datetime.datetime.strptime`. – FObersteiner Jul 22 '20 at 09:09
1

using datetime module, fromisoformat (most likely fastest option) to parse the string and timestamp() to get POSIX seconds since the epoch:

from datetime import datetime
s = '2019-06-17T19:17:45.000Z'
ts = datetime.fromisoformat(s.replace('Z', '+00:00')).timestamp()
#  1560799065.0

or strptime with appropriate format code:

ts = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f%z').timestamp()

...or dateutil's parser.parse (slower but even more convenient):

from dateutil.parser import parse
ts = parse(s).timestamp()
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat' I get this error while trying out the fastest option. – yahooo Jul 22 '20 at 10:33
  • @yahooo: are you sure your imports are correct? in the example, I only import the `datetime` class, not the whole datetime module – FObersteiner Jul 22 '20 at 10:40
  • yes I used the same imports that you gave. I copied those 3 lines into my notebook and it gave me this error. The second option to use parser.parse works correctly. – yahooo Jul 22 '20 at 10:45
  • 1
    @yahooo: btw. which Python version are you using? fromisoformat is Python 3.7+ ;-) – FObersteiner Jul 22 '20 at 10:45
  • Ah. Maybe thats the reason why. I am using python version 3.6.10. – yahooo Jul 22 '20 at 10:47
  • @yahooo: then maybe you can use `datetime.strptime`, see my edit of the answer. – FObersteiner Jul 22 '20 at 12:06