zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    父子传值
    第三次作业
    第二次作业
    最后一次作业--总结报告
    Vue项目axios请求设置responseType无效
    滚动条样式修改
    超出部分显示省略号,鼠标悬浮显示详细文本,el-tooltip
    大屏rem
    js比较时间大小
    kindeditor编辑器上传图片跨域
  • 原文地址:https://www.cnblogs.com/phpper/p/10449217.html
Copyright © 2011-2022 走看看