How to get part of string and pass it to other function in python?

前端 未结 4 490
一整个雨季
一整个雨季 2021-01-28 06:58

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

4条回答
  •  悲哀的现实
    2021-01-28 07:37

    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.

提交回复
热议问题