【问题标题】:How can you get the unix epoch timestamp in seconds from a given date and time in a given city?如何从给定城市的给定日期和时间获取 unix 纪元时间戳(以秒为单位)?
【发布时间】:2021-02-03 16:03:51
【问题描述】:

我正在尝试获取以下纽约日期和时间的相应 Epoch Unix 时间戳(以秒为单位):

2020-09-25 09:30 New York Time.

根据https://www.epochconverter.com/timezones?q=1601040600&tz=America%2FNew_York对应:

Conversion results (1601040600)
1601040600 converts to Friday September 25, 2020 09:30:00 (am) in time zone America/New York (EDT)

这是我尝试过的:

import datetime
import pytz
​
et = pytz.timezone('America/New_York')
​
mydt = datetime.datetime(2020,9,25,9,30,0,0,et)

​myepoch = int(mydt.timestamp())
​
print('2020-09-25 09:30 ET Epoch: ', myepoch)
​    ​
>>> OUTPUT
2020-09-25 09:30 ET Epoch:  1601043960
​

所以它给出了1601043960 而不是1601040600。为什么以及应该做些什么来获得正确的价值?

请注意,该解决方案适用于任何日期,因此它必须自动处理 EST/EDT 夏令时。

【问题讨论】:

  • 如果您可以访问地理数据库(例如 OSM/Nominatim),您甚至可以使用 geopy 查找城市坐标,使用 timezonefinder 获取该坐标的时区和然后获取当地时间。

标签: python datetime timezone python-datetime pytz


【解决方案1】:

似乎解决方案是这样的:

import datetime
import pytz
​
et = pytz.timezone('America/New_York')
​
mydt = et.localize(datetime.datetime(2020,9,25,9,30,0,0))

​myepoch = int(mydt.timestamp())
​
print('2020-09-25 09:30 ET Epoch: ', myepoch)
​    ​
>>> OUTPUT
2020-09-25 09:30 ET Epoch:  1601040600

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-03-17
  • 1970-01-01
  • 2017-01-10
  • 2020-04-11
  • 2016-09-06
  • 2018-08-03
  • 2014-03-14
  • 2023-04-01
相关资源
最近更新 更多