[英]Python3 how to raise a ValueError for a date time object if its not in the right format?
For a uni project we have to create a program conforming to some tests that we have been given. 对于uni项目,我们必须创建一个符合我们已经给出的一些测试的程序。 The tests use magic numbers as inputs for the functions. 测试使用幻数作为功能的输入。 I know how to get it to return a datetime object. 我知道如何获取它以返回一个datetime对象。 Just dont know how to raise the error! 只是不知道如何引发错误!
my code: 我的代码:
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
Test Code: 测试代码:
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))
these are the results i get: 这些是我得到的结果:
======================================================================
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
Any help would be much appreciated! 任何帮助将非常感激!
The error that you are making is that strptime raises a value error if the date string does not match the given format. 您所犯的错误是,如果日期字符串与给定格式不匹配,则strptime会引发值错误。 for example: 例如:
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 never gets set because strptime never returns a value. datetime_obj永远不会设置,因为strptime永远不会返回值。
Also, as noted, you are comparing the response from strptime to the inout string -- that will never work. 另外,如前所述,您正在比较从strptime到inout字符串的响应-永远不会起作用。
Try a simpler approach: 尝试一种更简单的方法:
import datetime
def time_to_datetime(datetimeSTR):
datetime_obj = datetime.datetime.strptime(datetimeSTR, '%Y/%m/%d %H:%M')
return datetime_obj
Or you can catch any exception and reraise (imo, bad practice, but might be worth doing to illustrate. 或者,您可以捕获任何异常并进行重新举报(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
This way, you see how strptime behaves for various inputs in your test and you have error handling in your function .... though, as I indicated, reraising an error is (imo) bad practice. 这样,您就可以看到strptime在测试中对各种输入的行为,并且在函数中有错误处理....但是,正如我所指出的,重新引发错误是(imo)不良做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.