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")
它触发错误-“ 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。
提前致谢!
解决方案
处理时区可能有点棘手。一种选择可能是从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'))
推荐阅读
- r - How can I order the bars in my histogram?
- python - How to add attribute to class before __init__?
- python - Create a directory in /var/lib
- javascript - 使用保存和新建按钮时如何保留父值
- php - 如何使用 laravel-websockets 使 URL 可用于在公共频道中注册?
- javascript - How to hide wrapped element using v-if
- vue.js - 如何使我的自定义 CSS 和 Javascript 文件在我的 vuejs 应用程序中工作
- c# - WPF Task.Run ==> 线程无法访问此对象
- spring - Jhipster Okta 离子
- c - ISO C String Concatenation unwanted @ character at the very end