【问题标题】:Python date string manipulation based on timezone - DST基于时区的 Python 日期字符串操作 - DST
【发布时间】:2013-07-05 05:29:58
【问题描述】:

我的目标是将字符串(包含 UTC 日期和时间)作为输入,并根据时区差异将其转换为本地时区。我想出了以下代码

代码

import time
print "Timezone Diff", time.timezone/3600

def convertTime(string):
        print "Before Conversion"
        print "year",string[0:4],"month",string[5:7],"day",string[8:10]
        print "hour",string[11:13],"min",string[14:16]
        print "After Conversion"
        print "newhour",int(string[11:13])-(time.timezone/3600)
        newhour = int(string[11:13])-(time.timezone/3600) 
        if newhour>=24:
            print "year",string[0:4],"month",string[5:7],"newday",int(string[8:10])+1
            print "hour",newhour-24,"min",string[14:16]
convertTime('2013:07:04:14:00')

输出:

Timezone Diff -10
Before Conversion
year 2013 month 07 day 04
hour 14 min 00
After Conversion
newhour 24
year 2013 month 07 newday 5
hour 0 min 00

此代码非常基本,显然不适用于月/年更改,也不考虑闰年。谁能建议我解决这个问题的更好方法。

【问题讨论】:

    标签: python python-2.7 timezone


    【解决方案1】:

    以下是datetimepytz 模块的解决方案,以我的时区为例:

    import pytz
    import datetime
    s = '2013:07:04:14:00'
    mydate = datetime.datetime.strptime(s, '%Y:%m:%d:%H:%M')
    mydate = mydate.replace(tzinfo=timezone('Australia/Sydney'))
    print mydate
    

    打印:

    2013-07-04 14:00:00+10:00
    

    您可能需要“重塑”代码才能获得准确的输出,但我希望这对您有所帮助!

    【讨论】:

    • ` import pytz ImportError: No module named pytz` can't import pytz
    • @misguided 是的,它不是标准库的一部分。看看here 如何下载它。或者去here,下载文件,然后运行python setup.py install
    • Mate 有没有办法让它在标准系统上工作?我无法在我的系统上下载和安装软件包。对不起:(
    • @misguided datetime 模块可能有一种方法(我在答案中链接了文档),但我不知道有任何方法可以这样做。对不起
    • 感谢您的回答。将在我的家庭系统上尝试这个以检查它是否有效:)
    【解决方案2】:

    要仅使用 stdlib 将 UTC 时间转换为本地时区,您可以使用中间时间戳值:

    from datetime import datetime
    
    def convertTime(timestring):
        utc_dt = datetime.strptime(timestring, '%Y:%m:%d:%H:%M')
        timestamp = (utc_dt - datetime.utcfromtimestamp(0)).total_seconds()
        return datetime.fromtimestamp(timestamp) # return datetime in local timezone
    

    How to convert a python utc datetime to a local datetime using only python standard library?

    要支持具有不同 UTC 偏移量的过去日期,您可能需要 pytztzlocal 库(仅 stdlib 的解决方案在 Ubuntu 上运行良好;基于 pytz 的解决方案也应该启用 Windows 支持):

    from datetime import datetime
    
    import pytz # $ pip install pytz
    from tzlocal import get_localzone # $ pip install tzlocal
    
    # get local timezone    
    local_tz = get_localzone()
    
    def convertTime(timestring):
        utc_dt = datetime.strptime(timestring, '%Y:%m:%d:%H:%M')
        # return naive datetime object in local timezone
        local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
        #NOTE: .normalize might be unnecessary
        return local_tz.normalize(local_dt).replace(tzinfo=None)
    

    【讨论】:

      【解决方案3】:

      下面的代码为我解决了这个问题。虽然pytz 可能是最好的使用方法。但是,如果您没有 pytz,则以下解决方案可能是一种替代方案。

      import datetime
      
          def convertTime(timestring):
              UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()
              local_datetime = datetime.datetime.strptime(timestring, "%Y:%m:%d:%H:%M")
              result_utc_datetime = local_datetime - UTC_OFFSET_TIMEDELTA
              print result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S"),
      
          s = '2013:07:07:14:00'
      
          convertTime(s)
      

      【讨论】:

      • 由于 DST 或 utc 偏移量因其他原因发生变化,您的解决方案对于具有不同 utc 偏移量(与当前日期不同)的过去日期失败。
      猜你喜欢
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多