Get timestamp for 27/02/2019 00:00 US/Eastern in p

2019-08-27 00:55发布

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条回答
smile是对你的礼貌
2楼-- · 2019-08-27 01:32

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.

查看更多
登录 后发表回答