【问题标题】:convert given time from a given timezone to UTC将给定时间从给定时区转换为 UTC
【发布时间】:2020-11-24 21:09:18
【问题描述】:

我有两个输入时间 00:00 和时区“亚洲/加尔各答”

我想将其转换为 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

请帮忙

【问题讨论】:

  • 当然时间没有转换,你正在转换到/从同一个时区!
  • 将 pytz 时区设置为本地时区,您当前将其存储为 UTC 时间的 00:00 并转换为 UTC 时间
  • 伙计们,我是 python 新手,我可以获取有关如何操作的参考代码吗?

标签: python timezone pytz


【解决方案1】:

类似这样的东西,假设你在 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>)
>>>

【讨论】:

    【解决方案2】:

    既然您说您是 Python 新手,最好跳过 pytz,因为它是 Python 3.9 的 going to be deprecated。您可以改用dateutil,在Python 3.9 中可以更轻松地替换为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()
    

    【讨论】:

      【解决方案3】:

      @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)
      

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-29
        • 2019-11-17
        • 2020-09-28
        • 2013-03-02
        • 2017-03-17
        相关资源
        最近更新 更多