IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> python转换非标准时间 -> 正文阅读

[Python知识库]python转换非标准时间

可匹配结构:

今天~前天, 几天前, 分钟秒前等 | 2017-1-4 12:10 | 2017/1/4 12:10 | 2018年4月2日 12:12 | 2018年4月2日 | 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):
    """
        时间匹配模块,可转化为固定格式
        返回时间字符串 0000-00-00 00:00:00
        可匹配结构 |今天~前天, 几天前,分钟秒前等 | 2017-1-4 12:10 | 2017/1/4 12:10 | 2018年4月2日 12:12
                        | 2018年4月2日 | 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)

        # 几/刚/今天/昨天/前天
        x = data.strip()
        x = x.replace(u'几', ' 0 ')
        x = x.replace(u'刚[刚才]', now.strftime(' %Y-%m-%d %H:%M:%S '))
        x = x.replace(u'今天', now.strftime(' %Y-%m-%d '))
        x = x.replace(u'昨天', now_1.strftime(' %Y-%m-%d '))
        x = x.replace(u'前天', now_2.strftime(' %Y-%m-%d '))
        x = re.sub(r'[年月]', '/', x)
        x = re.sub(r'[日]', ' ', x)
        x = re.sub(r'\s{2,}', r' ', x)

        # XX前
        res = (re.search(r'(?P<S>\d+)\s*秒钟?前', x) \
               or re.search(r'(?P<M>\d+)\s*分钟前', x) \
               or re.search(r'(?P<H>\d+)\s*小时前', x) \
               or re.search(r'(?P<d>\d+)\s*天前', 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))
            )
        # 不是几天前分钟前的形式
        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():
                # 匹配没有年份的时候,格式 XX-XX XX:XX:XX  月-日 时:分:秒 或 17年10月10日 时:分:秒
                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,
                    # 如果没有时分秒,则被认定为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 ""
        # 时间可能超过当前时间,若超过则减去一年
        if int(time.mktime((dt - offset).timetuple())) > int(time.time()):
            # 时间超过当前时间,减去一年
            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秒前', 'auto', ''))
    print(parse_date('2分钟前', 'auto', ''))
    print(parse_date('2小时前', 'auto', ''))
    print(parse_date('昨天 00:30', 'auto', ''))
    print(parse_date('07-20', 'auto', ''))
  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2021-07-25 11:36:25  更:2021-07-25 11:37:03 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年4日历 -2024/4/28 22:14:23-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码