将给定时间从给定时区转换为 UTC

convert given time from a given timezone to UTC

我有两个输入时间 00:00 和时区 'Asia/Kolkata'

我想将其转换为 UTC 时间,例如“18.30”

我不想增加或减少偏移量,因为它可能会影响夏令时

我做的是

 local = pytz.timezone ("UTC")
 nativetime = datetime.strptime (setTime,frmt)
 local_dt = local.localize(nativetime, is_dst=None)
 utc_dt = local_dt.astimezone(pytz.utc)

但这不会改变任何东西,时间不会转换为 UTC

请帮忙

像这样,假设你在 py3:

>>> import datetime
>>> import pytz
>>> tz = pytz.timezone('Asia/Kolkata')
>>> dt = datetime.datetime(2020, 8, 4, 0, 0, tzinfo=tz)
>>> dt.astimezone(pytz.utc)
datetime.datetime(2020, 8, 3, 18, 7, tzinfo=<UTC>)
>>>

既然你说你是 Python 的新手,跳过 pytz 可能会更好,因为它是 Python 3.9 中的 going to be deprecated with Python 3.9. You can use dateutil instead, which can be replaced more easily with zoneinfo

from datetime import datetime, timezone
from dateutil.tz import gettz

# assuming you have something like
dt_naive = datetime.strptime('2020-08-05', '%Y-%m-%d')

# dt_naive has no time zone info, so set it:
dt_aware = dt_naive.replace(tzinfo=gettz('Asia/Kolkata'))

# now you can convert to another timezone using .astimezone:
dt_aware_utc = dt_aware.astimezone(timezone.utc)

# datetime.datetime(2020, 8, 4, 18, 30, tzinfo=datetime.timezone.utc)
# -> 5:30 hours behind, which matches dt_aware.utcoffset()

@thebjorn 给了我答案

这是我做的

def utc_to_local(utc_dt,local_tz):
    local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
    return local_tz.normalize(local_dt)


setTime='00:00:00'
setZone='Asia/Kolkata'

datePart = str(datetime.utcnow()).split(' ')[0]
dateTimeUtcStr = datePart+' '+str(setTime)
tz = pytz.timezone('Asia/Kolkata')
tz_utc = pytz.timezone('UTC')
dateTimeRef = datetime.strptime(dateTimeUtcStr, '%Y-%m-%d %H:%M:%S')

#local to utc
tzUtc = pytz.timezone('UTC')
local_dt = tz.localize(dateTimeRef, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
print(utc_dt)

#utc to local
altTime = utc_to_local(utc_dt,tz)

print(altTime)