如何将包含无法识别时区的字符串转换为datetime?

2024-10-05 15:30:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将一个字符串解析为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")

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

问题是根据doc的说法,使用%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

提前谢谢


Tags: the字符串datetimestringbyisvalue格式
1条回答
网友
1楼 · 发布于 2024-10-05 15:30:27

处理时区可能有点棘手。一种选择是从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'))

相关问题 更多 >