Обнаружение формата даты и времени Python3 - PullRequest
0 голосов
/ 30 сентября 2018

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

Ответы [ 2 ]

0 голосов
/ 30 сентября 2018

Если цифры на ваших входах всегда 14 цифр, то вы можете использовать datetime.strptime с regex вместе с этим кодом, чтобы получить желаемый результат:

import re
from datetime import datetime


def get_integers(file_name, prefix='test_'):
    """Return matched integers"""
    regex = re.compile(r'{prefix}(\d+)'.format(prefix=prefix))
    matched = re.findall(regex, file_name)
    return matched[0] if matched else ''


def get_datetime_object(date_string):
    """Return datetime object from date_string if it exists"""
    try:
        date_object = datetime.strptime(date_string, '%Y%m%d%H%M%S')
        return date_object.strftime('%Y-%m-%d,%H:%M:%S')
    except ValueError:
        return None



file1 = 'test_20180101234523.txt'
integers = get_integers(file1)
date = get_datetime_object(integers)
print(date)

Выход:

2018-01-01,23:45:23

PS: Обратите внимание, что если целые числа на входе не содержат 14 цифр, то вам следует адаптировать функцию get_integers для возврата строки, содержащей 14 цифр.

0 голосов
/ 30 сентября 2018

Использовать datetime.strptime как (при условии, что выходное выражение регулярного выражения будет каждый раз иметь 14 цифр и следует тому же формату):

import datetime
date = datetime.datetime.strptime('20180101234523', '%Y%m%d%H%M%S')
date.strftime('%Y-%m-%d,%H:%M:%S')

'2018-01-01,23:45:23'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...