📜  获取 IST 时间的 UTC 时间 python (1)

📅  最后修改于: 2023-12-03 15:11:50.395000             🧑  作者: Mango

获取 IST 时间的 UTC 时间 Python

在 Python 中,我们可以使用 datetime 模块来获取当前的时间并进行转换。对于需要将印度标准时间 (IST) 转换为协调世界时 (UTC) 的情况,我们可以使用以下方法:

import datetime
import pytz

# 定义 IST 时区
ist = pytz.timezone('Asia/Kolkata')

# 获取当前时间并设定时区为 IST
ist_time = datetime.datetime.now(ist)

# 转换为 UTC 时间
utc_time = ist_time.astimezone(pytz.utc)

# 输出结果
print("IST 时间:", ist_time)
print("UTC 时间:", utc_time)

输出结果:

IST 时间: 2021-11-03 15:57:38.434570+05:30
UTC 时间: 2021-11-03 10:27:38.434570+00:00

以上代码中,我们使用 datetime.datetime.now() 函数获取当前时间,并将时区设定为 IST 所对应的时区。然后,使用 astimezone() 函数将 IST 时间转换为 UTC 时间。

另外,我们需要使用 pytz 模块来获取时区信息。在该模块中,我们可以使用 timezone() 函数来获取特定时区的信息。

注意,在使用以上代码之前,需要确保已经安装了 pytz 模块。可以通过以下命令来安装:

pip install pytz

以上就是获取 IST 时间的 UTC 时间的 Python 实现。