繁体   English   中英

Python3如果日期格式不正确,如何为日期时间对象引发ValueError?

[英]Python3 how to raise a ValueError for a date time object if its not in the right format?

对于uni项目,我们必须创建一个符合我们已经给出的一些测试的程序。 测试使用幻数作为功能的输入。 我知道如何获取它以返回一个datetime对象。 只是不知道如何引发错误!

我的代码:


    import datetime
    def time_to_datetime(datetimeSTR):
        datetime_obj = datetime.datetime.strptime(datetimeSTR, '%Y/%m/%d %H:%M')
        if datetimeSTR != datetime.datetime.strptime(datetimeSTR, '%Y/%m/%d %H:%M'):
            raise ValueError('The time must have the format YYYY/MM/DD HH:MM')
        else:
            return datetime_obj

测试代码:


    import datetime
    import os
    import unittest   # Standard unittest framework.

    import utils   # The module implementing JourneyOptions class.


    class TestTimeToDatetime(unittest.TestCase):
        """Tests for the time_to_datetime function."""

        def test_invalid_time_is_rejected(self):
            with self.assertRaises(ValueError) as cm:
                utils.time_to_datetime('2019/06/09 12:60')
            self.assertEqual(
                'The time must have the format YYYY/MM/DD HH:MM',
                str(cm.exception))

        def test_valid_time_yields_a_dattime_object(self):
            d = utils.time_to_datetime('2019/06/09 12:59')
            self.assertTrue(isinstance(d, datetime.datetime))

这些是我得到的结果:

======================================================================

ERROR: test_valid_time_yields_a_dattime_object (__main__.TestTimeToDatetime)

Traceback (most recent call last):
  File "C:/Users/s5115426/Desktop/tests/test_utils.py", line 21, in test_valid_time_yields_a_dattime_object
    d = utils.time_to_datetime('2019/06/09 12:59')
  File "C:\Users\s5115426\Desktop\tests\utils.py", line 25, in time_to_datetime
    raise ValueError('The time must have the format YYYY/MM/DD HH:MM')
ValueError: The time must have the format YYYY/MM/DD HH:MM

======================================================================
FAIL: test_invalid_time_is_rejected (__main__.TestTimeToDatetime)

Traceback (most recent call last):
  File "C:/Users/s5115426/Desktop/tests/test_utils.py", line 18, in test_invalid_time_is_rejected
    str(cm.exception))
AssertionError: 'The time must have the format YYYY/MM/DD HH:MM' != 'unconverted data remains: 0'
- The time must have the format YYYY/MM/DD HH:MM
+ unconverted data remains: 0

任何帮助将非常感激!

您所犯的错误是,如果日期字符串与给定格式不匹配,则strptime会引发值错误。 例如:

date_str = '2019/06/09 12:60'
datetime_obj = datetime.datetime.strptime(date_str, '%Y/%m/%d %H:%M')
.
.
ValueError: unconverted data remains: 0

datetime_obj永远不会设置,因为strptime永远不会返回值。

另外,如前所述,您正在比较从strptime到inout字符串的响应-永远不会起作用。

尝试一种更简单的方法:

import datetime
def time_to_datetime(datetimeSTR):
    datetime_obj = datetime.datetime.strptime(datetimeSTR, '%Y/%m/%d %H:%M')
    return datetime_obj

或者,您可以捕获任何异常并进行重新举报(imo,不好的做法,但可能值得说明。

import datetime
def time_to_datetime(datetimeSTR):
    try:
        datetime_obj = datetime.datetime.strptime(datetimeSTR, '%Y/%m/%d %H:%M')
    except ValueErr as err:
        print(err)
        raise ValueError('The time must have the format YYYY/MM/DD HH:MM')
    else:
        return datetime_obj

这样,您就可以看到strptime在测试中对各种输入的行为,并且在函数中有错误处理....但是,正如我所指出的,重新引发错误是(imo)不良做法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM