Skip to content Skip to sidebar Skip to footer

Change Time Format For A String

I want to write a function to change the time format and an offset is used to shift the date For example, I have a string 'this is a string 2012-04-12 23:55 with a 2013-09-12 time

Solution 1:

Your error is caused by you trying to call report.groups(); you never applied the regular expression on the report parameter.

Your code can be simplified significantly:

_dt = re.compile(r"""
    [12]\d{3}-   # Year (1xxx or 2xxx),
    [0-1]\d-     # month (0x, 1x or 2x)
    [0-3]\d      # day (0x, 1x, 2x or 3x)
    (?:\s        # optional: time after a space
        [0-2]\d: # Hour (0x, 1x or 2x)
        [0-5]\d  # Minute (0x though to 5x)
    )?
    """, flags=re.VERBOSE)

def_deIDReportDate(report, offset=654321):
    defreplace(match):
        dt = match.group()

        iflen(dt) > 10:
            # with time
            dt = datetime.datetime.strptime(dt, '%Y-%m-%d %H:%M')
            dt += datetime.timedelta(seconds=offset)
            return dt.strftime('%d-%b-%Y %H:%M')

        dt = datetime.datetime.strptime(dt, '%Y-%m-%d')
        dt += datetime.timedelta(seconds=offset)
        return dt.strftime('%d-%b-%Y')

    return _dt.sub(replace, report)

The replace nested function is called for each non-overlapping match in the input string.

Post a Comment for "Change Time Format For A String"