My task is to verify whether string is valid date and time or not.
\"2013-01-01W23:01:01\"
The date and the time are separated with
If all you need to do is to check whether the string in the format you specified is a valid datetime or not, no need to split it and pass values to some handmade functions, just use this:
from datetime import datetime
try:
valid_datetime = datetime.strptime('2013-01-01W23:01:01', '%Y-%m-%dW%H:%M:%S')
print 'this datetime is valid'
except ValueError:
print 'this datetime is invalid'
You can try this ,
>>> a="2013-01-01W23:01:01"
>>> a.split('W')
['2013-01-01', '23:01:01']
And then send a.split('W')[0]
and a.split('W')[1]
to the validation functions.
Use str.partition() to get the first part, fast:
value.partition('W')[0]
You could use str.split() as well, for Python versions < 2.5. Limit the split to just the first W
:
value.split('W', 1)[0]
Either technique will always yield a result, even if there is no 'W'
character in value
.
Demo:
>>> value = "2013-01-01W23:01:01"
>>> value.partition('W')[0]
'2013-01-01'
>>> value.split('W', 1)[0]
'2013-01-01'
If you are not sure whether it is a valid date or time, you should use regular expressions to validate the string, then you don't even need to call is_time
and is_date
.
import re
pattern = re.compile("^(\d{4}-\d{2}-\d{2})[W ](\d{2}:\d{2}:\d{2})$")
# ...
value = "2013-01-01W23:01:01"
match = pattern.findall(value)
if match:
pass #is valid
This will test whether something looks like a date&time.
You can of course use more advanced regexes.
^(\d{4}-(11|12|0\d)-(3[10]|[12]\d))[W ]((2[0-3]|[01]\d):[0-5]\d:[0-5]\d)$
This one tests for valid date and time values (so it doesn't match 27:99:01 anymore), but still matches invalid dates, like 2014-02-31. If you want to exclude those cases, you can access the relevant parts of the match as items of the match
variable and test for things like number of days of a month and leap years.