日期时间格式检测Python3

时间:2018-09-30 09:33:31

标签: python regex python-3.x date datetime

例如,我想使用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 :(得分:2)

使用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'

答案 1 :(得分:1)

如果输入中的数字始终为14位,则可以将datetime.strptimeregex一起使用,并结合以下代码以获取所需的输出:

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位数字的字符串。