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
.
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.
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.
There are two parts:
#!/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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With