gpt4 book ai didi

python - 如何在Python中将本地时间的日期/时间字符串转换为UTC?

转载 作者:太空宇宙 更新时间:2023-11-03 16:24:31 27 4
gpt4 key购买 nike

我正在尝试编写一个函数,在 Python 中将字符串日期/时间从本地时间转换为 UTC。

根据this question ,您可以使用 time.tzname 来获取某些形式的本地时区,但我还没有找到在任何日期时间转换方法中使用它的方法。例如,this article显示您可以使用 pytzdatetime 执行一些操作来转换时间,但它们都具有硬编码的时区,并且格式与time.tzname返回。

目前我有以下代码将字符串格式的时间转换为毫秒(Unix 纪元):

local_time = time.strptime(datetime_str, "%m/%d/%Y %H:%M:%S") # expects UTC, but I want this to be local
dt = datetime.datetime(*local_time[:6])
ms = int((dt - datetime.datetime.utcfromtimestamp(0)).total_seconds() * 1000)

但是,这需要以 UTC 形式输入时间。有没有办法将字符串格式的时间转换为本地时区?谢谢。

本质上,我希望能够做this answer确实如此,但我希望能够动态指定本地时区,而不是在“America/Los_Angeles”中进行硬编码。

最佳答案

如果我正确理解你的问题,你想要这个:

from time import strftime,gmtime,mktime,strptime

# you can pass any time you want
strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(strptime("Thu, 30 Jun 2016 03:12:40", "%a, %d %b %Y %H:%M:%S"))))

# and here for real time
strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(strptime(strftime("%a, %d %b %Y %H:%M:%S"), "%a, %d %b %Y %H:%M:%S"))))

关于python - 如何在Python中将本地时间的日期/时间字符串转换为UTC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38111921/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com