如何将当地时间的 date/time 字符串转换为 Python 的 UTC?

How can I convert a date/time string in local time into UTC in Python?

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

根据 this question, you can use time.tzname to get some forms of the local timezone, but I have not found a way to use this in any of the datetime conversion methods. For example, this article 显示,您可以使用 pytzdatetime 做一些事情来转换时间,但它们都有硬编码的时区并且是与 time.tznamereturns 不同的格式。

目前我有以下代码将字符串格式的时间转换为毫秒(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"))))

从时间元组创建时间结构,然后使用该结构创建 utc 时间

from datetime import datetime

def local_to_utc(local_st):
    time_struct = time.mktime(local_st)
    utc_st = datetime.utcfromtimestamp(time_struct)
    return utc_st

d=datetime(2016,6,30,3,12,40,0)
timeTuple = d.timetuple()
print(local_to_utc(timeTuple))

输出:

2016-06-30 09:12:40