是否存在可以修复错误时间格式的模块?

时间:2019-01-25 02:26:12

标签: python datetime

我的数据格式如下: 12/07/2018 23:00 12/07/2018 24:00 13/07/2018 1:00 并且想知道python中是否存在可以将12/07/2018 24:00更改为13/07/2018 0:00

的模块

2 个答案:

答案 0 :(得分:2)

这将为您涵盖所有情况,假设您的dateformat字符串是静态的:

from datetime import datetime, timedelta

def fix_time(time_string):
    if '24:00' in time_string:  # Does time_string contain silly format
        _date, _ = time_string.split()  # Ignore time part since it will default to 00:00
        calendar_date= datetime.strptime(_date, '%d/%m/%Y')
        corrected_time = calendar_date + timedelta(days=1)  # Add one day to get correct date
        time_string = corrected_time.strftime('%d/%m/%Y %H:%M')  # Convert back to str
    return time_string

示例输出:

  

fix_time('31 / 12/2018 24:00')
> '01 / 01/2019 00:00'

可以使代码更简洁,但这应该是一个很好的起点。

答案 1 :(得分:-1)

功能:

def fix_terrible(x):
    year, hour = x.split(" ")
    year = year.split("/")
    if "24" in hour:
        hour = "0:00"
        year[0] = str(1+int(year[0]))
    if year[0] == "32":
        year[1] = str(1+int(year[1]))
        year[0] = "1"
    if year[0] == "31" and year[1] in ["09","04","06","11"]:
        year[1] = str(1+int(year[1]))
        year[0] = "1"
    if year[0] == "29" and year[1] == "02":
        year[1] = str(1+int(year[1]))
        year[0] = "1"
    if year[1] == "13":
        year[1] = "01"
        year[2] = str(1+int(year[2]))
    return "/".join(year) + " " + hour