• Python3 日期与时间戳相互转换


    开发中经常会对时间格式处理,对于时间数据,比如2019-02-28 10:23:29,有时需要日期与时间戳进行相互转换,在Python3中主要用到time模块,相关的函数如下:

    其中unix_time函数是正常时间转unix时间戳,date_time是unix时间转正常时间如年月日时分秒:

    import time
    
    """
    日期转时间戳
    """
    
    
    def unix_time(dt):
        # 转换成时间数组
        timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
        # 转换成时间戳
        timestamp = int(time.mktime(timeArray))
        return timestamp
    
    
    """
    时间戳转日期
    """
    
    
    def custom_time(timestamp):
        # 转换成localtime
        time_local = time.localtime(timestamp)
        # 转换成新的时间格式(2016-05-05 20:28:54)
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        return dt
    
    
    time_now = '2019-02-28 10:23:29'
    unix_t = unix_time(time_now)
    custom_t = custom_time(unix_t)
    print(unix_t)  # 1551320609
    print(custom_t)  # 2019-02-28 10:23:29
    
    # 如果是自定义的时间格式转换呢,思路方法雷同,比如下:
    """
    时间用指定格式显示,比如 年-月-日 转 年/月/日
    """
    dt = "2020-10-10 22:20:20"
    # 转为数组
    timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
    # 转为其它显示格式
    customTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
    print(customTime)  # 2020/10/10 22:20:20
    
    """
    时间用指定格式显示,比如 年/月/日 转 年-月-日
    """
    dt = "2020/10/10 22:20:20"
    timeArray = time.strptime(dt, "%Y/%m/%d %H:%M:%S")
    customTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
    print(customTime)  # 2020-10-10 22:20:20
  • 相关阅读:
    Web API DataContract DataMember Serializable简单解释
    v-bind和v-on
    CSS大写转换
    Web API 实体显示注释
    Web API性能优化(一)压缩
    时间序列化问题
    border 0px和border none的区别
    CSS实现单行、多行文本溢出显示省略号
    MySQL防止重复插入记录SQL
    mvc和webapi同一解决方案调试办法
  • 原文地址:https://www.cnblogs.com/phpper/p/10449217.html
Copyright © 2020-2023  润新知