例如,我想使用python3进行日期格式检测
我有file1 = "test_20180101234523.txt"
并且输出应该是格式类型%Y%M%D%H%m%S
和预期的日期时间格式2018-01-01,23:45:23
以下是我目前所做的
import re
file1 = "test_20180101234523.txt"
pattern = r'[0-9]{14}'
regex=re.compile(pattern)
matches = regex.findall(file1)
matchesStr = matches[0]
matchesYear = int(matchesStr[0:4])
matchesMonth = int(matchesStr[4:6])
matchesdate = int(matchesStr[6:8])
matchesH = int(matchesStr[8:10])
matchesM = int(matchesStr[10:12])
matchesS = int(matchesStr[12:14])
def checkdate():
if matchesYear > 1900:
print("%Y")
else:
print("Year is not format")
if matchesMonth >= 1 and matchesMonth <= 12:
print("%M")
else:
print("Month is not format")
if matchesdate >= 1 and matchesdate <= 31:
print("%d")
else:
print("Date is not format")
if matchesH >= 1 and matchesH <= 24:
print("%H")
else:
print("Hour is not a format")
if matchesM >= 1 and matchesM <= 60:
print("%m")
else:
print("Min is not a format")
if matchesS >= 1 and matchesS <= 60:
print("%S")
else:
print("Sec is not a format")
我使用regex找出整数组,并将其作为我需要的每个变量的子字符串。并使用if-else条件来检查每一个。 如果你们还有其他的想法,请分享一下好吗?在
使用^{} as(假设regex输出每次都是14位数字,格式相同):
如果输入中的数字总是14位数字,那么您可以使用}一起使用,以获得所需的输出:
datetime.strptime
与{输出:
^{pr2}$PS:注意,如果输入中的整数是'nt14位数,那么您应该使用
get_integers
函数返回包含14位数的字符串。在相关问题 更多 >
编程相关推荐