我有一个UTC时间作为字符串,我想把它转换成UTC时间戳.但下面的代码似乎再次将其转换为UTC,导致它是错误的TimeStap.如何将日期时间格式转换为时间戳,以便将其保留为UTC.

datetime.strptime('2023-08-02 14:52:05', '%Y-%m-%d %H:%M:%S').timestamp() * 1000

Input time GMT: 2023-08-02 14:52:05  
Outputs GMT: 1691002325000.0     
# This converts to GMT: Wednesday, August 2, 2023 6:52:05 PM https://www.epochconverter.com/

推荐答案

TL;DR:使用

datetime.fromisoformat(f"{utc_time_string}+00:00").timestamp() * 1000

你对这个错误的观察是正确的.And that's because:

Naive 100 instances are assumed to represent local time,并且该方法依赖于平台C mktime()功能来执行转换.

这些文档还展示了如何从表示UTC的朴素DateTime对象中获取时间戳:

timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

因此,您可以这样做:

(
    datetime
        .strptime('2023-08-02 14:52:05', '%Y-%m-%d %H:%M:%S')
        .replace(tzinfo=timezone.utc)
        .timestamp() * 1000
)

输出1690987925000.0等于GMT: Wednesday, August 2, 2023 2:52:05 PM

由于您的DATETIME字符串看起来几乎是ISO的,因此您还可以在转换前使用.fromisoformat()并在字符串末尾添加"+00:00".它将生成一个支持TZ的DateTime对象,并由.timestamp()正确处理:

utc_time_string = '2023-08-02 14:52:05'
(
    datetime
        .fromisoformat(f"{utc_time_string}+00:00")
        .timestamp() * 1000
)
# fits nicely on one line
datetime.fromisoformat(f"{utc_time_string}+00:00").timestamp() * 1000

也输出1690987925000.0.

Python 3.11 onwards, you can add the suffix "Z",而不是"+00:00".

Python相关问答推荐

如何让 turtle 通过点击和拖动来绘制?

标题:如何在Python中使用嵌套饼图可视化分层数据?

PMMLPipeline._ fit()需要2到3个位置参数,但给出了4个位置参数

数据抓取失败:寻求帮助

我如何根据前一个连续数字改变一串数字?

把一个pandas文件夹从juyter笔记本放到堆栈溢出问题中的最快方法?

调用decorator返回原始函数的输出

Django admin Csrf令牌未设置

幂集,其中每个元素可以是正或负""""

如何防止Pandas将索引标为周期?

在输入行运行时停止代码

搜索按钮不工作,Python tkinter

判断Python操作:如何从字面上得到所有decorator ?

一个telegram 机器人应该发送一个测验如何做?""

提取数组每行的非零元素

我什么时候应该使用帆布和标签?

为什么dict. items()可以快速查找?

了解如何让库认识到我具有所需的依赖项

将时间序列附加到数据帧

Django REST框架+Django Channel->;[Errno 111]连接调用失败(';127.0.0.1';,6379)