日期时间格式检测Python3

2024-06-06 03:29:39 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我想使用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条件来检查每一个。 如果你们还有其他的想法,请分享一下好吗?在


Tags: andformatifis格式notfile1else
2条回答

使用^{}as(假设regex输出每次都是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'

如果输入中的数字总是14位数字,那么您可以使用datetime.strptime与{}一起使用,以获得所需的输出:

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)

输出:

^{pr2}$

PS:注意,如果输入中的整数是'nt14位数,那么您应该使用get_integers函数返回包含14位数的字符串。在

相关问题 更多 >