How to get UTC epoch value from a local timestamp

2019-02-21 04:51发布

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.

1条回答
冷血范
2楼-- · 2019-02-21 05:21

A good way to get seconds since epoch is to do it explicitly. This function converts the timestring to a naive datetime, makes the datetime timezone aware, and then subtracts a datetime which is epoch at UTC.

Code:

import datetime as dt
from pytz import timezone

def convert_timestamp_to_utc_epoch(ts, tz_info):
    # convert timestamp string to naive datetime
    naive = dt.datetime.strptime(ts, '%Y-%m-%d %H:%M:%S')

    # assign proper timezone to datetime
    aware = tz_info.localize(naive)

    # get a datetime that is equal to epoch in UTC
    utc_at_epoch = timezone('UTC').localize(dt.datetime(1970,1,1))

    # return the number of seconds since epoch
    return (aware - utc_at_epoch).total_seconds()

Test Code:

Using the example from question:

print('CET:',
    convert_timestamp_to_utc_epoch('2017-02-22 17:04:06', timezone('CET')))

Results:

CET: 1487779446.0

Get an arbitrary local timezone:

If you are not sure what timezone the local machine is using, the tzlocal library can be used like:

from tzlocal import get_localzone
local_tz = get_localzone()
print('Local:', 
    convert_timestamp_to_utc_epoch('2017-02-22 17:04:06', local_tz))
print('Pacific:', 
    convert_timestamp_to_utc_epoch('2017-02-22 17:04:06', timezone('US/Pacific')))

Results:

Local: 1487811846.0
Pacific: 1487811846.0
查看更多
登录 后发表回答