【问题标题】:How can I detect time in a String in Python and the Convert the time into a different timezone?如何在 Python 中检测字符串中的时间并将时间转换为不同的时区?
【发布时间】:2021-02-18 18:53:22
【问题描述】:

假设有一个字符串 --->

"I eat potato at 5:30 PM"

所以,我想做的是从字符串中捕获时间5:30 PM,并在它完成捕获时间之后(5:30 PM 并假设时区为 'America/New_York' 格式),它会将其转换为不同的时区(假设采用 'UTC' 格式)。

如何在 Python 中做到这一点?

【问题讨论】:

    标签: python pandas string date datetime


    【解决方案1】:

    为了在文本中捕捉时间,您可以使用带有 re 模块的正则表达式。 (https://docs.python.org/3/library/re.html)

    对于日期和时间的操作,使用 datetime 模块。 (https://docs.python.org/3/library/datetime.html#timezone-objects)

    【讨论】:

    • 您可以添加 zoneinfo 来处理时区(pytz 已经过时,因为它是使用 Python 3.9 添加到标准库中的)。
    【解决方案2】:
    from datetime import datetime
    import pytz
    
    utc = pytz.utc
    eastern = pytz.timezone('US/Eastern')
    
    # Using datetime1 from the question
    datetime1 = datetime.strptime(somestring, "%Y-%m-%dT%H:%M:%S")
    
    # First, tell Python what timezone that string was in (you said Eastern)
    eastern_time = eastern.localize(datetime1)
    
    # Then convert it from Eastern to UTC
    utc_time = eastern_time.astimezone(utc)
    

    【讨论】:

      【解决方案3】:

      使用pytz.datetime:

      from datetime import datetime
      import pytz
      utc = pytz.utc
      eastern = pytz.timezone('US/Eastern')
      datetime1 = datetime.strptime(somestring, "%Y-%m-%dT%H:%M:%S")
      easternTime = eastern.localize(datetime1)
      utcTime = easternTime.astimezone(utc)
      

      【讨论】:

        【解决方案4】:

        我猜你总是可以假设你试图捕捉的时间就是这种格式。

        HH:MM PM/AM

        所以你可以做类似的事情

        example_str = "I eat potato at 5:30 PM"
        
        def extract_time(str):
            str_lst = str.split()
            for i, elem in enumerate(str_lst):
                if elem == "PM":
                    hour = int(str_lst[i-1].split(":")[0]) + 12
                    min = int(str_lst[i-1].split(":")[1])
                    return hour, min
                if elem == "AM":
                    hour = int(str_lst[i-1].split(":")[0])
                    min = int(str_lst[i-1].split(":")[1])
                    return hour, min
            return None
                    
        

        如果你这样做

        extract_time(example_str)
        

        它会返回 (17, 30)。

        现在您可以使用Python Timezone conversion 此处的示例来转换时区。

        【讨论】:

          【解决方案5】:

          您可以使用pytz 模块:

          import pytz, datetime
          import re
          
          s = "I eat potato at 5:30 PM"
          d = re.findall('[\d ]\d:\d\d \w\w', s)[0].strip()
          
          utc_dt = pytz.timezone("America/New_York").localize(datetime.datetime.strptime(d, "%H:%M %p"), is_dst=None).astimezone(pytz.utc)
          print(f'{utc_dt.hour}:{utc_dt.minute}')
          

          输出:

          10:26
          

          【讨论】:

            【解决方案6】:

            由于问题被标记为pandas,我假设其中包含时间的字符串是pd.Series 或pd.DataFrame 的一部分。另请注意,如果您没有日期,则无法明确地将时间与时区相关联 - 只需考虑 DST。

            与其他答案类似,在 pandas 中,您将使用正则表达式提取时间,解析为 datetime 并关联/更改时区/UTC:

            import pandas as pd
            
            df = pd.DataFrame({'strings':["I eat potato at 5:30 PM"]})
            
            # add a date,
            # extract the time with a suitable regex,
            # parse to datetime
            date = '2020-11-06 '
            df['USEastern_dt'] = pd.to_datetime(date + df['strings'].str.extract('(\d{1,2}\:\d{2}\ [A-P]{2})')[0])
            
            # localize to US/Eastern
            df['USEastern_dt'] = df['USEastern_dt'].dt.tz_localize('US/Eastern')
            
            # convert to UTC
            df['UTC_dt'] = df['USEastern_dt'].dt.tz_convert('UTC')
            

            ...这会给你

            df['UTC_dt']
            0   2020-11-06 22:30:00+00:00
            Name: UTC_dt, dtype: datetime64[ns, UTC]
            

            【讨论】:

              猜你喜欢
              • 2021-05-06
              • 1970-01-01
              • 1970-01-01
              • 2021-07-12
              • 1970-01-01
              • 2021-10-17
              • 1970-01-01
              • 2016-10-12
              • 1970-01-01
              相关资源
              最近更新 更多