zoukankan      html  css  js  c++  java
  • Sublime Text3时间戳查看转换插件开发

    平常配置表中,经常需要用到时间配置,比如活动开始结束。从可读性上,我们喜欢2017-04-27 17:00:00,从程序角度,我们喜欢用1493283600。前者是包含时区概念的,而后者时区无关,所以一般推荐直接使用数字时间戳格式来配置。

    实际配置时,之前一直用MySQL的FROM_UNIXTIME()UNIX_TIMESTAMP函数,或者使用网页工具进行时间戳查看转换,十分繁琐。

    做得多了,就想到为什么不写个插件,直接在编辑器里查看转换好了。参考了网络上的一些示例并查阅了Sublime的相关API,过程如下。

    1.依次执行Tools -> Developer -> New Plugin,新建一个插件脚本,命名为timestamp.py

    2.添加脚本代码,具体可以看注释:

        from datetime import datetime
        import re
        import time
        import sublime
        import sublime_plugin
    
        def getParseResult(text):
            #patten1 匹配10位整数时间戳(1493283600)
            pattern1 = re.compile('^d{10}')
            match1 = pattern1.match(text)
    
            #pattern2 匹配可读时间格式(2017-04-27 17:00:00)
            pattern2 = re.compile('^(d{4})-(d{1,2})-(d{1,2})s(d{1,2}):(d{1,2}):(d{1,2})')
            match2 = pattern2.match(text)
    
            if text in ('now'):
                result = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            elif text in ('ts', 'timestamp'):
                result = str(time.time()).split('.')[0]
            elif match1:
                timestamp = int(match1.group(0))
                timeArray = time.localtime(timestamp)
                result = time.strftime('%Y-%m-%d %H:%M:%S', timeArray)
            elif match2:
                timeArray = time.strptime(text, "%Y-%m-%d %H:%M:%S")
                result = str(time.mktime(timeArray)).split('.')[0]
            return result
    
        class TimestampCommand(sublime_plugin.TextCommand):
            def run(self, edit):
                for s in self.view.sel():
                    if s.empty() or s.size() <= 1:
                        break
    
                    # 只处理第一个Region
                    text = self.view.substr(s)
                    print(text)
    
        			# 得到转换结果
                    result = getParseResult(text)
    
                    # 进行文本替换并弹窗显示
                    self.view.replace(edit, s, result)
                    self.view.show_popup(result, sublime.HIDE_ON_MOUSE_MOVE_AWAY, -1, 600, 600)
                    break
    

    3.进行快捷键绑定,依次执行Preferences -> Key Bindings,添加代码{ "keys": ["ctrl+t"], "command": "timestamp"}

    很简单,一个方便查看转换时间戳的插件就写好了。选中文本,按快捷键CTRL+t,效果图:

    代码放在了Github,更多欢迎访问个人网站Metazion

  • 相关阅读:
    推广项目难点-隐藏IP上
    推广项目难点之数据清洗
    推广项目难点之数据随机分发
    推广项目新架构测试报告
    notepad++正则表达式
    MySQL查询时构建自增ID
    ASP.NET MVC页面UI之多级数据选择UI(行业信息、专业信息、职位信息的选择)
    DesignMode_EasyFactory
    Arithmetic_Thinking -- greedy algorithm
    JDBC--SQL(DDL)
  • 原文地址:https://www.cnblogs.com/kaleovon/p/8963520.html
Copyright © 2011-2022 走看看