Я хочу использовать 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")
Я использую регулярное выражение, чтобы найти группу целых чисел и подстроку, чтобы они были каждой переменной, которая мне нужна.И используйте условие if-else для проверки каждого из них.Если у вас есть какая-нибудь другая идея, не могли бы вы поделиться, пожалуйста?