使用 pytz 和 datetime 在 python 中获取 27/02/2019 00:00 US/Eastern 的时间戳 [英] Get timestamp for 27/02/2019 00:00 US/Eastern in python using pytz and datetime

查看:75
本文介绍了使用 pytz 和 datetime 在 python 中获取 27/02/2019 00:00 US/Eastern 的时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串:

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

我试过了:

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

我已检查 1551225600 时间戳对应于 27/02/2019 00:00 UTC 而不是 27/02/2019 00:00 US/使用这个服务的东东:

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/

我做错了什么?

推荐答案

为了帮助其他人,我发现错误位于此处:

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())

EPOCH 时间应使用 UTC 时区:

It shall use UTC timezone for the EPOCH time:

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

通过这样做,您将获得 1551243600 作为时间戳,它对应于 Wednesday, 27 February 2019 05:00:00 UTC,实际上是 27/02/2019 00:00 美国/东部时间

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.

这篇关于使用 pytz 和 datetime 在 python 中获取 27/02/2019 00:00 US/Eastern 的时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆