【问题标题】:How to convert UTC to EST with Python and take care of daylight saving automatically?如何使用 Python 将 UTC 转换为 EST 并自动处理夏令时?
【发布时间】:2018-07-03 03:30:14
【问题描述】:

如果我在UTC format 中有一堆包含日期和时间的数据,如何将它们转换为EST

它可以每年自动确定它们何时是-4(in summer)和-5(in winter)? 谢谢

【问题讨论】:

    标签: python datetime datetime-format python-datetime


    【解决方案1】:

    您需要使用 pytz 模块(可从 PyPI 获得):

    import pytz
    from datetime import datetime
    
    est = pytz.timezone('US/Eastern')
    utc = pytz.utc
    fmt = '%Y-%m-%d %H:%M:%S %Z%z'
    
    winter = datetime(2016, 1, 24, 18, 0, 0, tzinfo=utc)
    summer = datetime(2016, 7, 24, 18, 0, 0, tzinfo=utc)
    
    print winter.strftime(fmt)
    print summer.strftime(fmt)
    
    print winter.astimezone(est).strftime(fmt)
    print summer.astimezone(est).strftime(fmt)
    

    将打印:

    2016-01-24 18:00:00 UTC+0000
    2016-07-24 18:00:00 UTC+0000
    2016-01-24 13:00:00 EST-0500
    2016-07-24 14:00:00 EDT-0400
    

    您需要使用'US/Eastern' 而不是'EST' 的原因在最后两行输出中举例说明。

    【讨论】:

    • "winter=" 和 "summer=" 是否用于设置特定日期的夏令时或冬令时?如果是的话,如果我有超过 10000 个不同的日期,这是不可能的。另外,每年都不一样,使用这种方法,是不是需要找出每年时间变化的确切日期?
    • 不,winter 和 summer 只是变量名称,用于指出一个日期在 1 月,另一个在 7 月。
    • 谢谢!你的回答很有帮助!
    【解决方案2】:

    如果您有一个对象数据类型的 pandas 系列,您可以先使用 pd.to_datetime() 将其转换为 DateTime 系列

    df[col] = pd.to_datetime(your_series, format = '%Y-%m-%d %H:%M:%S', errors ='coerce')
    

    使用series.dt.tz检查它是否支持时区

    df[col].dt.tz
    

    如果它不支持时区,我们应该使用series.dt.tz_localize() 使其支持时区。另外,请阅读有关此函数的模棱两可和不存在的参数

    df[col] = your_series[col].dt.tz_localize('UTC')
    

    现在通过series.dt.tz_convert()将此系列转换为所需的时区

    df[col] = your_series[col].dt.tz_convert('US/Eastern')
    

    上述方法将处理夏令时。如果你想检查更多时区,你可以 pip install pytz 和

    import pytz
    pytz.common_timezones
    

    【讨论】:

      【解决方案3】:

      如上所述,您可以像这样使用pandas.DataFrame.tz_convert()

      import pandas as pd
      from datetime import datetime
      
      df = pd.read_csv("your_data_file_path.csv", index_col=False, engine='python')
      df['Date'] = pd.to_datetime(df['Date'])
      df['Date'] = df['Date'].dt.tz_localize('US/Eastern').dt.tz_convert('UTC')
      df['Date'] = df['Date'].apply(lambda x: datetime.replace(x, tzinfo=None))
      

      最后一行的作用是从 datetime 对象中删除时区信息,因此您可以仅使用日期和时间进行操作(不用担心,这不会再次更改时区,它只是将其从时间戳中剥离字符串)。

      【讨论】:

        【解决方案4】:

        如果您只想要现有时间增量偏移的标准化小时偏移量:

        from datetime import datetime
        import pytz
        
        def curr_est_offset():
            tz_est = pytz.timezone('US/Eastern')
            offset = tz_est.utcoffset(datetime.utcnow())
            offset_seconds = (offset.days * 86400) + offset.seconds
            offset_hours = offset_seconds // 3600
        
            return offset_hours # -4 or -5
        

        【讨论】:

          【解决方案5】:

          这是 thebjorn 的答案,它从 Python 2 转换为 Python 3 并添加了一些额外的 cmets。感谢 thebjorn。

          为了约定,我使用这些术语:

          • EST:东部标准时间(冬季)
          • EDT:东部夏令时间 (夏季)
          • EPT:东部通行时间(标准或夏令时 时间视情况而定)

          代码

          # Convert EPT / UTC
          
          # Timezones
          ept = pytz.timezone('US/Eastern')
          utc = pytz.utc
          # str format
          fmt = '%Y-%m-%d %H:%M:%S %Z%z'
          
          print("\nEPT/UTC examples:")
          print("\nWinter (EST) example:")
          # Create a UTC time in the winter
          winter_utc = dtdt(2016, 1, 24, 18, 0, 0, tzinfo=utc)
          print("    UTC: ", winter_utc.strftime(fmt))
          # Convert from UTC to eastern prevailing time.  Since, the timestamp is in the
          # winter, prevailing time is standard time.
          winter_ept = winter_utc.astimezone(ept)
          print("    EPT: ", winter_ept.strftime(fmt))
          # Let's convert back to UTC to show we get back to the original value.
          winter_utc2 = winter_ept.astimezone(utc)
          print("    UTC: ", winter_utc2.strftime(fmt))
          
          # Let's do that again for a summer datetime.
          print("\nSummer (EDT) example:")
          summer_utc = dtdt(2016, 7, 24, 18, 0, 0, tzinfo=utc)
          print("    UTC: ", summer_utc.strftime(fmt))
          # Convert from UTC to eastern prevailing time.  Since, the timestamp is in the
          # winter, prevailing time is daylight saving time.
          summer_ept = summer_utc.astimezone(ept)
          print("    EPT: ", summer_ept.strftime(fmt))
          # Let's convert back to UTC to show we get back to the original value.
          summer_utc2 = summer_ept.astimezone(utc)
          print("    UTC: ", summer_utc2.strftime(fmt))
          

          控制台

          EPT/UTC examples: 
          
          Winter (EST) example:
              UTC:  2016-01-24 18:00:00 UTC+0000
              EPT:  2016-01-24 13:00:00 EST-0500
              UTC:  2016-01-24 18:00:00 UTC+0000 
          
          Summer (EDT) example:
              UTC:  2016-07-24 18:00:00 UTC+0000
              EPT:  2016-07-24 14:00:00 EDT-0400
              UTC:  2016-07-24 18:00:00 UTC+0000
          

          【讨论】:

            猜你喜欢
            • 2020-06-22
            • 2021-11-04
            • 2023-04-07
            • 2021-11-15
            • 2021-10-27
            • 2015-08-04
            • 1970-01-01
            • 2014-06-01
            • 2017-09-10
            相关资源
            最近更新 更多