Pythonic way to check time input (only for Hr, Min, Sec)

In my application, I get time input in a variable in string format, for example. Values = '12,12,12' .

Now I need to check it h<24 M<60 S<60 etc., and I want the final output in the format '%H:%M:%S' .
To get this, I tried datetime.time().

I tried 1 time with values = '12' , then '12,12,12' .

 In [1]: import datetime In [2]: values = '12' In [3]: d = datetime.time(values) TypeError Traceback (most recent call last) /mypc/test/<ipython console> in <module>() TypeError: an integer is required In [4]: d = datetime.time(int(values)) In [5]: d Out[5]: datetime.time(12, 0) In [6]: d.strftime('%H:%M:%S') Out[6]: '12:00:00' In [7]: s = d.strftime('%H:%M:%S') In [8]: s Out[8]: '12:00:00' In [9]: values = '12,12,12' In [10]: d = datetime.time(int(values)) ValueError: invalid literal for int() with base 10: '12,12,12' 

But it works as shown below.

 In [24]: datetime.time(12,12,12).strftime('%H:%M:%S') Out[24]: '12:12:12' 

So the problem is that datetime.time () accepts the input as a whole, and the string '12,12,12' cannot be converted to int.

Is there another way (another, regexp) to check only for Hr: M: S.

+4
source share
2 answers

You need to unpack the values:

 >>> values = '12,12,12' >>> values = ast.literal_eval(values) >>> datetime.time(*values) datetime.time(12, 12, 12) 

This last statement will throw an error if the specified time is not valid.

To avoid problems with null numbers, as "wim" indicated, you can change the second line to:

 values = (int(i) for i in values.split(',')) 

or

 values = map(int, values.split(',')) 
+5
source

Note that the copy of strftime is equal to strptime , that is, if you need to analyze the time you can use strptime using the format string in the same way you use strftime to print the time using this format string:

 >>> import time >>> t = time.strptime('12,12,12', '%H,%M,%S') >>> time.strftime('%H:%M:%S', t) '12:12:12' 

So strptime does the check ( H<24, M<60, S<=61 ):

 >>> time.strptime('24,0,0', '%H,%M,%S') ... ValueError: time data '24,0,0' does not match format '%H,%M,%S' >>> time.strptime('0,60,0', '%H,%M,%S') ... ValueError: time data '0,60,0' does not match format '%H,%M,%S' >>> time.strptime('0,0,62', '%H,%M,%S') ... ValueError: unconverted data remains: 2 

Note that strptime allows S<=61 , as described in the documentation :

The range is valid from 0 to 61; this explains leap seconds and (very rare) double leap seconds.

If this is a problem for you, you probably need to parse this value in your code.

+5
source

Source: https://habr.com/ru/post/1391197/


All Articles