change time format for a string

后端 未结 1 1873
闹比i
闹比i 2021-01-21 03:04

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          


        
相关标签:
1条回答
  • 2021-01-21 03:38

    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):
        def replace(match):
            dt = match.group()
    
            if len(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.

    0 讨论(0)
提交回复
热议问题