首页 > 解决方案 > 如何将包括无法识别的时区的字符串转换为日期时间?

问题描述

我需要将一个字符串解析为python datetime,以这种格式接收的字符串 - Thu Jul 15 12:57:35 AWST 2021

我使用下面的代码来解析它

datetime.datetime.strptime("Thu Jul 15 12:57:35 AWST 2021", "%a %b %d %H:%M:%S %Z %Y")

它触发错误-“ ValueError:时间数据'Thu Jul 15 12:57:35 AWST 2021'与格式'%a %b %d %H:%M:%S %Z %Y'不匹配

根据文档,问题是使用%Z无法识别时区 AWST

%Z
In strftime(), %Z is replaced by an empty string if tzname() returns None; otherwise %Z is replaced by the returned value, which must be a string.

strptime() only accepts certain values for %Z:

any value in time.tzname for your machine’s locale

the hard-coded values UTC and GMT

如何正确解析此字符串?顺便说一句,我使用的是 python 3.8.2。

提前致谢!

标签: pythonpython-3.xdatetime

解决方案


处理时区可能有点棘手。一种选择可能是从https://www.timeanddate.com/time/zones/制作感兴趣的时区地图,然后用于dateutils.parser解析日期。就像是 :

使用 UTC 偏移量:

from dateutil import parser

# Creating a sample map for the timezone abbreviation and the offset
timezone_info = {
        "A": 1 * 3600,
        "AT": -4 * 3600,
        "AWDT": 9 * 3600,
        "AWST": 8 * 3600,
        "AZOST": 0 * 3600,
        "AZOT": -1 * 3600,
        "AZST": 5 * 3600,
        "AZT": 4 * 3600,
        "AoE": -12 * 3600,
        "B": 2 * 3600,
        "BNT": 8 * 3600,
        "BST": 6 * 3600,
        "C": 3 * 3600,
        "CAST": 8 * 3600,
        "CET": 1 * 3600,
        "W": -10 * 3600,
        "WEST": 1 * 3600,
        "WET": 0 * 3600,
        "WST": 14 * 3600,
        "Z": 0 * 3600,
}

#Date String
date = "Thu Jul 15 12:57:35 AWST 2021"

# parse the timezone info from the date string
tz = date.split(" ")[-2] # Assuming the date format is"%a %b %d %H:%M:%S %Z %Y"
parser.parse(date, tzinfos={tz : timezone_info.get(tz)})

输出:

datetime.datetime(2021, 7, 15, 12, 57, 35, tzinfo=tzoffset('AWST', 28800))

使用 IANA 时区名称:(正如@MrFuppes 在评论中所建议的那样)

from dateutil import parser

# Creating a sample map for the timezone abbreviation and the offset
timezone_info = {
    "AWST": 'Australia/Perth',
    "BNT": 'Asia/Brunei',
    "CAST": 'Antarctica/Casey',
    "CET": 'Europe/Paris'
}

#Date String
date = "Thu Jul 15 12:57:35 AWST 2021"

# parse the timezone info from the date string
tz = date.split(" ")[-2] # Assuming the date format is"%a %b %d %H:%M:%S %Z %Y"
parser.parse(date, tzinfos={tz : timezone_info.get(tz)})

输出:

datetime.datetime(2021, 7, 15, 12, 57, 35, tzinfo=tzstr('Australia/Perth'))

推荐阅读