尝试捕获块中的两种不同的 ValueError 类型?

2024-05-13 22:05:09 发布

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

我正在开发一个函数来处理pandasdataframe中的时间戳。这些时间戳的时区偏移量必须始终介于-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()的时间戳字符串就是字符串“other”。你知道吗

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来对每个案例应用不同的处理?你知道吗


Tags: inparserstringreturnparseline时间tz
1条回答
网友
1楼 · 发布于 2024-05-13 22:05:09

您可以检查异常消息以找出确切原因:

def rogue_tz_offsets(t):
   try:
       d = dateutil.parser.parse(t)
       if -12 * 60 * 60 <= d.utcoffset().total_seconds() <= 14 * 60 * 60:
          return d.isoformat()
       return d.replace(tzinfo=None).isoformat()

   except ValueError as e:
       if str(e) == 'Unknown string format':
           return dateutil.parser.parse('2100-01-01 00:00:00').isoformat()

       if str(e) == 'offset must be a timedelta strictly between -timedelta(hours=24) and timedelta(hours=24).':
           return dateutil.parser.parse(t).replace(tzinfo=None).isoformat()

相关问题 更多 >