Get timestamp for 27/02/2019 00:00 US/Eastern in python using pytz and datetime

℡╲_俬逩灬. 提交于 2019-12-11 17:19:08

问题


I have the following string:

27/02/2019

As it is known in the program that those dates correspond to NY time zone, I would like to get the timestamp corresponding to:

27/02/2019 00:00 US/Eastern

I have tried:

import datetime
import pytz

exchange_tz = pytz.timezone('US/Eastern')
_period1 = datetime.datetime(2019,2,27)
_period1_localized = exchange_tz.localize(_period1)
_period1_ts = int((_period1_localized - datetime.datetime(1970, 1, 1, tzinfo=exchange_tz)).total_seconds()) 

>>> _period1_ts
1551225600

But this gives the timestamp corresponding to:

27/02/2019 00:00 UTC

I have checked that 1551225600 timestamp corresponds to 27/02/2019 00:00 UTC and not to 27/02/2019 00:00 US/Eastern using this service:

https://www.epochconverter.com/

What am I doing wrong?


回答1:


Just in case it helps others, I found the error was located here:

_period1_ts = int((_period1_localized - datetime.datetime(1970, 1, 1, tzinfo=exchange_tz)).total_seconds())

It shall use UTC timezone for the EPOCH time:

_period1_ts = int((_period1_localized - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds())

By doing that you get 1551243600 as timestamp, which corresponds to Wednesday, 27 February 2019 05:00:00 UTC which is effectively 27/02/2019 00:00 US/Eastern time

The above code with this correction can be used to get a timestamp from a localized datetime.



来源:https://stackoverflow.com/questions/54912487/get-timestamp-for-27-02-2019-0000-us-eastern-in-python-using-pytz-and-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!