【发布时间】:2019-12-22 22:47:34
【问题描述】:
我正在开发一个函数来处理 pandas dataframe 中的时间戳。这些时间戳的时区偏移量必须始终介于 -12 和 +14 之间。
声音时间戳字符串偏移示例:
x = '2019-11-11T07:08:09.640-4:00'
无意义的时间戳字符串偏移示例:
y = '2019-11-11T07:08:09.640-31:00'
然后当我尝试格式化它们时(工作正常):
dateutil.parser.parse(x).isoformat()
'2019-11-11T07:08:09.640000-04:00'
但是然后是无意义的时区偏移(不起作用):
dateutil.parser.parse(y).isoformat()
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: offset must be a timedelta strictly between -timedelta(hours=24) and timedelta(hours=24).
所以,我尝试制作一个使用 try 的函数,但 ValueError 除外:
def rogue_tz_offsets(t):
try:
return dateutil.parser.parse(t).isoformat()
except ValueError:
return dateutil.parser.parse(t).replace(tzinfo=None).isoformat()
例如
rogue_tz_offsets('2019-11-11T07:08:09.640-31:00')
'2019-11-11T07:08:09.640000'
很好,这行得通,无意义的时区偏移量 -31 已被删除。现在有一个合理的时区偏移:
rogue_tz_offsets('2019-11-11T07:08:09.640-4:00')
'2019-11-11T07:08:09.640000-04:00'
好的,这次保留声音时区偏移-4:00。
到目前为止一切顺利,除了我的数据中还有一种情况,其中要传递给rogue_tz_offsets() 的时间戳字符串只是字符串“其他”。
rogue_tz_offsets('other')
Traceback (most recent call last):
File "<input>", line 7, in rogue_tz_offsets
File "/usr/local/lib/python3.7/site-packages/dateutil/parser/_parser.py", line 1358, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "/usr/local/lib/python3.7/site-packages/dateutil/parser/_parser.py", line 649, in parse
raise ValueError("Unknown string format:", timestr)
ValueError: ('Unknown string format:', 'other')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 9, in rogue_tz_offsets
File "/usr/local/lib/python3.7/site-packages/dateutil/parser/_parser.py", line 1358, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "/usr/local/lib/python3.7/site-packages/dateutil/parser/_parser.py", line 649, in parse
raise ValueError("Unknown string format:", timestr)
ValueError: ('Unknown string format:', 'other')
对我来说问题是它是一个ValueError,我已经考虑过了。在这种情况下,如果我能够区分ValueError 的两种类型,我想返回:
return dateutil.parser.parse('2100-01-01 00:00:00').isoformat()
所以只需将其设置为遥远的未来日期。
我的完整功能:
def rogue_tz_offsets(t):
try:
return dateutil.parser.parse(t).isoformat()
except ValueError:
# handle case where the t is the string 'other'
return dateutil.parser.parse('2100-01-01 00:00:00').isoformat()
except ValueError:
# handle the case where the timezone offset is out of range by removing it
return t.replace(tzinfo=None).isoformat()
如何区分ValueError 的两种类型以对每种情况应用不同的处理方式?
【问题讨论】:
-
嗯,您可能需要实际检查错误消息。当然,这是一种笨拙的方法。