python - 将时间转换为 EpochSecond
问题描述
我是 python 新手。目前,我有一个像“2018-11-15 13:34:40.000 EST”这样的时间数据。我想把它转换成EpochSecond。
我知道如何使用 dateparser 来获得这个,但是,我想知道有没有一种简单的方法可以在没有 dateparser 的情况下做到这一点?
import dateparser
from datetime import datetime, timezone
mytime = "2018-11-15 13:34:40.000 EST"
dateVar = dateparser.parse(mytime)
print(dateVar)
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
print((dateVar - epoch).total_seconds())
解决方案
datetime.datetime.timestamp()
是您正在寻找的(相关部分):
对于感知日期时间实例,返回值计算为:
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
例子:
import datetime
now = datetime.datetime.now()
epoch = now.timestamp()
# 1542394106.155199
实施到您的示例中,我们将不得不使用另一种方法,因为由于错误(我在哪里找到信息的相关问题datetime.datetime.strptime()
)而不太友好地采用时区。所以我们必须使用另一个内置函数来解析它(这里的例子):
from dateutil.parser import parse
mytime = "2018-11-12 00:30:20.000 EST"
dt = parse(mytime)
epoch = dt.timestamp()
解析后的字符串仍然是一个datetime.datetime
对象,因此您可以在解析后对其进行相同的处理。
注意:但是parse
可能会抱怨它读取了时区但不理解它:
UnknownTimezoneWarning: tzname EDT identified but not understood. Pass `tzinfos` argument in order to correctly return a timezone-aware datetime. In a future version, this will raise an exception.
无论如何,您最终可能需要将传递给tzinfos
该parse()
方法:
from dateutil.parser import parse
# from dateutil.tz import gettz # <-- can use if you know the tz to retrieve
tzinfos = {'EST': -18000, 'CET': +3600}
# another example: {"CST": gettz("America/Chicago")}
mytime = "2018-11-12 00:30:20.000 EST"
dt = parse(mytime, tzinfos=tzinfos)
epoch = dt.timestamp()
print(epoch)
所以我想最终它并不像你想要的那么简单。
推荐阅读
- html - 我无法更改产品价格以下的后缀
- php - 带有重写条件的 PHP 表单脚本
- javascript - 在控制台中工作但不是来自脚本的代码
- flutter - 如何在没有 admob 的情况下在颤振中添加广告?
- angular - ng2-Dragula 和 Angular5 - Copy 有效,copySortSource 不能可靠地工作
- elasticsearch - Kibana 中的查询不返回带有正则表达式的日志
- python - 汇总矩阵中的每个列值
- python - 如何在 Python 中从 DataFrame 中绘制图像(以 PIL 格式)?
- c++ - 声明后是否必须清除 C++ 向量?
- javascript - 在执行以下代码时,JS 中出现错误:“参数列表后未捕获语法错误:缺少)”