Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert python timestamp string to epoch?

Tags:

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.

like image 775
Rolando Avatar asked May 26 '15 20:05

Rolando


People also ask

How do I convert timestamp to epoch?

Convert from human-readable date to epochlong epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds. date +%s -d"Jan 1, 1980 00:00:01" Replace '-d' with '-ud' to input in GMT/UTC time.

How do you convert date object to epoch time in Python?

Use the timegm Function to Convert DateTime to Epoch in Python. The timegm() function takes a specific time value and returns its corresponding Unix timestamp value. The epoch is taken as 1970, and the POSIX encoding is assumed. time.


1 Answers

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).

like image 137
jfs Avatar answered Sep 27 '22 22:09

jfs