如何使用pytz和datetime库将具有区域/城市时区格式的时间字符串转换为UTC?

huangapple go评论62阅读模式
英文:

How can I convert a time string with region/city timezone format to UTC using pytz and datetime libraries?

问题

我正在处理格式为 Tue, 27 Dec 2022 21:01:54 Region/City 的时间字符串,除了 Region/City 部分之外,其余部分可以以多种方式格式化,如 27-Dec-202227 Dec 2022

我想将此字符串转换为UTC格式,即 DAY, DD MM YYYY HH:MM:SS GMT

我正在使用pytz和datetime库进行操作,但不确定如何继续:


import datetime as dt
import pytz

def convert_timezone(date_str):
    if any((match_tz := tz) in date_str for tz in pytz.all_timezones):
        date_str_notz = date_str.replace(match_tz, "")
        print(date_str_notz)
        for date_frmt in [
            "%a, %d %b %Y %H:%M:%S",
            "%a, %d-%b-%Y %H:%M:%S",
        ]:
            naive_time = dt.datetime.strptime(date_str_notz, date_frmt)

        local_tz = pytz.timezone(match_tz)
        local_time = local_tz.localize(naive_time, is_dst=None)
        utc_time = local_time.astimezone(pytz.utc)
        return(utc_time)

result=convert_timezone("Tue, 27 Dec 2022 21:01:54 Asia/Kolkata")
print(result)

但是这会产生错误:

Tue, 27 Dec 2022 21:01:54 
Traceback (most recent call last):
  File "/home/user/Git/github/data/url.py", line 21, in <module>
    result=convert_timezone("Tue, 27 Dec 2022 21:01:54 Asia/Kolkata")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/Git/github/data/url.py", line 13, in convert_timezone
    naive_time = dt.datetime.strptime(date_str_notz, date_frmt)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.11/_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.11/_strptime.py", line 352, in _strptime
    raise ValueError("unconverted data remains: %s" %
ValueError: unconverted data remains:  

然而,以下代码似乎可以正常工作:


>>> datetime.datetime.strptime('Tue, 27 Dec 2022 21:01:54', '%a, %d %b %Y %H:%M:%S')
datetime.datetime(2022, 12, 27, 21, 1, 54)
>>> 

英文:

I'm working with times formatted as Tue, 27 Dec 2022 21:01:54 Region/City, the part except Region/City can be formatted in any number of ways like 27-Dec-2022 or 27 Dec 2022.

I want to convert this string to UTC format ie. DAY, DD MM YYYY HH:MM:SS GMT

I'm using the pytz and datetime library for this and I'm not sure how to proceed after this:


import datetime as dt
import pytz

def convert_timezone(date_str):
    if any((match_tz := tz) in date_str for tz in pytz.all_timezones):
        date_str_notz = date_str.replace(match_tz, &quot;&quot;)
        print(date_str_notz)
        for date_frmt in [
            &quot;%a, %d %b %Y %H:%M:%S&quot;,
            &quot;%a, %d-%b-%Y %H:%M:%S&quot;,
        ]:
            naive_time = dt.datetime.strptime(date_str_notz, date_frmt)

        local_tz = pytz.timezone(match_tz)
        local_time = local_tz.localize(naive_time, is_dst=None)
        utc_time = local_time.astimezone(pytz.utc)
        return(utc_time)

result=convert_timezone(&quot;Tue, 27 Dec 2022 21:01:54 Asia/Kolkata&quot;)
print(result)

But this gives the error:

Tue, 27 Dec 2022 21:01:54 
Traceback (most recent call last):
  File &quot;/home/user/Git/github/data/url.py&quot;, line 21, in &lt;module&gt;
    result=convert_timezone(&quot;Tue, 27 Dec 2022 21:01:54 Asia/Kolkata&quot;)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File &quot;/home/user/Git/github/data/url.py&quot;, line 13, in convert_timezone
    naive_time = dt.datetime.strptime(date_str_notz, date_frmt)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File &quot;/usr/lib64/python3.11/_strptime.py&quot;, line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File &quot;/usr/lib64/python3.11/_strptime.py&quot;, line 352, in _strptime
    raise ValueError(&quot;unconverted data remains: %s&quot; %
ValueError: unconverted data remains:  

However this seems to work fine:


&gt;&gt;&gt; datetime.datetime.strptime(&#39;Tue, 27 Dec 2022 21:01:54&#39;, &#39;%a, %d %b %Y %H:%M:%S&#39;)
datetime.datetime(2022, 12, 27, 21, 1, 54)
&gt;&gt;&gt; 

答案1

得分: 0

我从你提供的代码中注意到你正在分离时区和日期字符串。在使用 replace(match_tz, &quot;&quot;) 方法进行分离时,你在日期字符串后留下了一个额外的空格。这会导致 datetime.strptimee() 函数失败,因为它无法找到指定的格式。为了解决这个问题,可以在最后使用 strip() 方法。

你的代码流程:

  1. date_str = &quot;Tue, 27 Dec 2022 21:01:54 Asia/Kolkata&quot;
  2. replace() 函数之后,date_str_notz = &quot;Tue, 27 Dec 2022 21:01:54 &quot;

我的代码流程:

  1. date_str = &quot;Tue, 27 Dec 2022 21:01:54 Asia/Kolkata&quot;
  2. replace() 函数之后,date_str_notz = &quot;Tue, 27 Dec 2022 21:01:54&quot;
英文:

From the code provided by you I noticed you are separating the time zone and and date string. While you are separating them using replace(match_tz,&quot;&quot;) method you are leaving a extra space after to the date_str string. This causes the datetime.strptimee() function to fail as it can't find the specified format. To overcome this use strip() method at the end.

    date_str_notz = date_str.replace(match_tz, &quot;&quot;).strip()

Your code flow:

  1. date_str = &quot;Tue, 27 Dec 2022 21:01:54 Asia/Kolkata&quot;
  2. After replace() function date_str_notz = &quot;Tue, 27 Dec 2022 21:01:54 &quot;

My code flow:

  1. date_str = &quot;Tue, 27 Dec 2022 21:01:54 Asia/Kolkata&quot;
  2. After replace() function date_str_notz = &quot;Tue, 27 Dec 2022 21:01:54&quot;

huangapple
  • 本文由 发表于 2023年6月2日 11:26:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76386946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定