Conversion of non-standard time in Python

Time:2021-10-11

Matching structure:

Today ~ the day before yesterday, a few days ago, minutes and seconds ago, etc. | 2017-1-4 12:10 | 2017 / 1 / 4 12:10 | April 2, 2018 12:12 | April 2, 2018 | 2017-1-4 | 2017 / 1 / 4 | 1 / 4|

# -*- coding:utf-8 -*-
from datetime import datetime, timedelta
import re
import time


def tz_offset(tz):
    res = (re.search(r'(?P<F>[-+])(?P<H>\d{2}):?(?P<M>\d{2})', tz) or re.search('', '')).groupdict()
    offset = (1 if res.get('F', '+')=='+' else -1) * timedelta(
                        hours   = int(res.get('H', 0)),
                        minutes = int(res.get('M', 0)))
    return offset


def parse_date(data, fmt, tz):
    """
        Time matching module, which can be converted into fixed format
        Return time string 0000-00-00 00:00:00
        Matching structure | today ~ the day before yesterday, a few days ago, minutes and seconds ago | 2017-1-4 12:10 | 2017 / 1 / 4 12:10 | April 2, 2018 12:12
                        |April 2, 2018 | 2017-1-4 | 2017 / 1 / 4 | 1 / 4|
    """
    offset = tz_offset(tz)
    if fmt == 'auto':
        now = (datetime.utcnow() + timedelta(hours=8)).replace(microsecond=0) + offset
        now_1 = now - timedelta(days=1)
        now_2 = now - timedelta(days=2)

        #What day / just / today / yesterday / the day before yesterday
        x = data.strip()
        X = x.replace (U ',' 0 ')
        X = x.replace (U 'just [just]', now.strftime ('% Y -% m -% d% H:% m:% s'))
        X = x.replace (U 'today', now.strftime ('% Y -% m -% d'))
        X = x.replace (U 'yesterday', now_1. Strftime ('% Y -% m -% d'))
        X = x.replace (U 'day before yesterday', now_2.strftime ('% Y -% m -% d'))
        X = re.sub (R '[year]', '/', x)
        X = re.sub (R '[day]', ', x)
        x = re.sub(r'\s{2,}', r' ', x)

        #Before XX
        Res = (re. Search (R '(? P < s > \ D +) \ s * seconds ago', x)\
               Or re. Search (R '(? P < m > \ D +) \ s * minutes ago', x)\
               Or re. Search (R '(? P < H > \ D +) \ s * hours ago', x)\
               Or re. Search (R '(? P < d > \ D +) \ s * days ago', x)\
               or re.search('', '')).groupdict()
        if res:
            dt = now - timedelta(
                days=int(res.get('d', 0)),
                hours=int(res.get('H', 0)),
                minutes=int(res.get('M', 0)),
                seconds=int(res.get('S', 0))
            )
        #Not in the form of a few minutes ago
        else:
            # XX-XX-XX XX:XX:XX
            res = (re.search(r'(?P<Y>\d+)[/-](?P<m>\d+)[/-](?P<d>\d+)(\s+(?P<H>\d{1,2}):(?P<M>\d{2})(:(?P<S>\d{2}))?)?',
                             x) or re.search('', '')).groupdict()
            if res == dict():
                #When there is no year matching, the format is XX-XX XX: XX: XX month day hour: minute: second or October 10, 2017 hour: minute: second
                res = (re.search(
                    r'(?P<m>\d{1,2})[/-](?P<d>\d+)(\s+(?P<H>\d{2}):(?P<M>\d{2})(:(?P<S>\d{2}))?)?',
                    x) or re.search('', '')).groupdict()
            if res:
                Y = res.get('Y', now.year)
                Y = "20" + Y if len(str(Y)) == 2 else Y
                m = res.get('m', now.month)
                d = res.get('d', now.day)
                H = res.get('H', now.hour)
                M = res.get('M', now.minute)
                S = res.get('S', 0)
                dt = datetime(
                    year=int(Y) if Y != None and 1987 <= int(Y) <= now.year else now.year,
                    month=int(m) if m != None else now.month,
                    day=int(d) if d != None else now.day,
                    #If there are no hours, minutes and seconds, it is considered as 00:00:00
                    hour=int(H) if H != None else 0,
                    minute=int(M) if M != None else 0,
                    second=int(S) if S != None else 0
                )
            else:
                # 1970-01-01 00:00:00
                # dt = datetime.utcfromtimestamp(0)+offset
                return ""
        #The time may exceed the current time. If it exceeds the current time, subtract one year
        if int(time.mktime((dt - offset).timetuple())) > int(time.time()):
            #If the time exceeds the current time, subtract one year
            delta = timedelta(days=-365)
            real_time = (dt - offset) + delta
            real_time = real_time.strftime("%Y-%m-%d %H:%M:%S")
        else:
            real_time = (dt - offset).strftime("%Y-%m-%d %H:%M:%S")
        return real_time


if __name__ == '__main__':
    Print (parse_date ('2 seconds ago ',' auto ',' '))
    Print (parse_date ('2 minutes ago ',' auto ',' '))
    Print (parse_date ('2 hours ago ',' auto ',' '))
    Print (parse_date ('Yesterday 00:30 ','auto', ''))
    print(parse_date('07-20', 'auto', ''))

This is the end of this article on the transformation of Python non-standard time. For more information about Python non-standard time, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

Centos8.4 installing confluence7.13 md

Reference 1:https://blog.whsir.com/post-5854.htmlReference 2:https://confluence.atlassian.com/confkb/confluence-basic-nginx-configurations-for-proxy-load-balancing-logging-1019381716.htmlReference 3:https://confluence.atlassian.com/conf73/running-confluence-behind-nginx-with-ssl-991928804.html System environment and installation preparation System version database Application software CPU Memory CentOS 8.4 MySQL 8.0.21 Confluence 7.13.0 16 cores 16G Confluence 7.13 download from the official website MySQL drive connection Cracking tool download jdk-8u301-windows-x64.exeThis is to run the cracking tool #Kernel parameter optimization VIM /etc/sysctl conf net.ipv4.ip_forward = 0 net.ipv4.conf.default.rp_filter […]