How to convert python timestamp string to epoch?

Rolando picture Rolando · May 26, 2015 · Viewed 56.1k times · Source

I have the following string:

mytime = "2009-03-08T00:27:31.807Z"

How do I convert it to epoch in python?

I tried:

import time
p = '%Y-%m-%dT%H:%M:%S'
int(time.mktime(time.strptime(s, p)))

But it does not work with the 31.807Z.

Answer

jfs picture jfs · May 27, 2015

There are two parts:

  1. Convert the time string into a broken-down time. See How to parse ISO formatted date in python?
  2. Convert the UTC time to "seconds since the Epoch" (POSIX timestamp).
#!/usr/bin/env python
from datetime import datetime

utc_time = datetime.strptime("2009-03-08T00:27:31.807Z", "%Y-%m-%dT%H:%M:%S.%fZ")
epoch_time = (utc_time - datetime(1970, 1, 1)).total_seconds()
# -> 1236472051.807

If you are sure that you want to ignore fractions of a second and to get an integer result:

#!/usr/bin/env python
import time
from calendar import timegm

utc_time = time.strptime("2009-03-08T00:27:31.807Z", "%Y-%m-%dT%H:%M:%S.%fZ")
epoch_time = timegm(utc_time)
# -> 1236472051

To support timestamps that correspond to a leap second such as Wed July 1 2:59:60 MSK 2015, you could use a combination of time.strptime() and datetime (if you care about leap seconds you should take into account the microseconds too).