I need to convert my timestamp into an epoch value. I found that my system timezone is set to CET, which is also used by my my-sql database.
I tried this:
os.environ['TZ']='UTC'
epoch = int(time.mktime(time.strptime('2017-02-22 17:04:06', '%Y-%m-%d %H:%M:%S')))
print(epoch)
#Output: 1487779446 -> not the same compared to 1487779446000 (= '2017-02-22 17:04:06')
print(time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(epoch/1000.)))
#Output: 01/18/1970 05:16:19 -> Not Correct!
# Timestamp: '2017-02-22 17:04:06'
print(time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(1487779446000/1000.)))
#Output: 02/22/2017 16:04:06 -> Correct!
I tried this with CET too, same result. I don't understand why I am getting different values.
A good way to get seconds since epoch is to do it explicitly. This function converts the timestring to a naive
datetime
, makes thedatetime
timezone aware, and then subtracts adatetime
which is epoch at UTC.Code:
Test Code:
Using the example from question:
Results:
Get an arbitrary local timezone:
If you are not sure what timezone the local machine is using, the
tzlocal
library can be used like:Results: