我正试图编写一个Python函数,将传入的时间戳标准化为
yyyy-mm-ddThh:mm+/-tz offset
.
例子:
def format_ts(ts):
beg_format = [
'%H:%M%a, %b %d, %Y %Z',
'%a, %d %b %Y %H:%M:%S %z',
]
end_format = '%Y-%m-%dT%H:%M %z'
try:
for f in beg_format:
if datetime.strptime(ts, f):
ts_fmt = datetime.strptime(ts, f)
ts_fmt = ts_fmt.strftime(end_format)
return ts_fmt
except:
pass
ts = [
'08:27Sun, Dec 19, 2021 IST',
'Sun, 19 Dec 2021 02:28:56 +0000'
]
for t in ts:
formatted_ts = format_ts(t)
print(formatted_ts)
问题:
-
IIRC,我不应该依赖失败(
pass
),而是应该捕获异常并进行处理
-
上述函数通过所有格式迭代所有时间戳(慢)
-
除非我错过了什么,
IST
没有人读
%Z
-
出于某种原因,
'%a, %d %b %Y %H:%M:%S %z'
不适用于的格式不正确
ts[1]
问题:
其他人是如何在Python中处理此类问题的?