zoukankan      html  css  js  c++  java
  • Python时间,日期,时间戳之间转换,时间转换时间戳,Python时间戳转换时间,Python时间转换时间戳

    #1.将字符串的时间转换为时间戳方法:
    a = "2013-10-10 23:40:00"
    #将其转换为时间数组
    import time
    
    timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
    # 转换为时间戳:
    timeStamp = int(time.mktime(timeArray))
    timeStamp == 1381419600
    #一行代码的写法是
    timeStamp = int(time.mktime(time.strptime(a, "%Y-%m-%d %H:%M:%S")))
    # 字符串格式更改如a = "2013-10-10 23:40:00", 想改为a = "2013/10/10 23:40:00"
    # 方法:先转换为时间数组, 然后转换为其他格式
    timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
    otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
    
    # 3.时间戳转换为指定格式日期:
    # 方法一:利用localtime()转换为时间数组, 然后格式化为需要的格式, 如
    timeStamp = 1381419600
    timeArray = time.localtime(timeStamp)
    otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
    # otherStyletime == "2013-10-10 23:40:00"
    #一行代码的写法
    otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(timeStamp))
    # 方法二:
    import datetime
    timeStamp = 1381419600
    dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
    otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
    # otherStyletime == "2013-10-10 23:40:00"
    
    # 4.获取当前时间并转换为指定日期格式
    # 方法一:
    import time
    
    # 获得当前时间时间戳
    now = int(time.time())  #这是时间戳转换为其他日期格式, 如:"%Y-%m-%d %H:%M:%S"
    timeArray = time.localtime(timeStamp)
    otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
    
    # 方法二:
    import datetime
    
    # 获得当前时间
    now = datetime.datetime.now()  #这是时间数组格式转换为指定的格式:
    otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
    
    # 5. 获得三天前的时间
    # 方法:
    import time
    import datetime
    
    # 先获得时间数组格式的日期
    threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days=3))
    # 转换为时间戳:
    timeStamp = int(time.mktime(threeDayAgo.timetuple()))
    # 转换为其他字符串格式:
    otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")
    # 注:timedelta()的参数有:days, hours, seconds, microseconds
    
    # 6.给定时间戳, 计算该时间的几天前时间:
    timeStamp = 1381419600
    # 先转换为datetime
    import datetime
    import time
    
    dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
    threeDayAgo = dateArray - datetime.timedelta(days=3)
    

      注意事项: 1.Python的时间戳长度是10个数字,Java的长度是13个数字。我们在做时间戳转换的时候可以 乘以一千或者除以一千

            2. Python 中的 %Y-%m-%d %H:%M:%S 可以根据自己的需要进行修改

    
    

    本文链接:http://www.cnblogs.com/xuchunlin/p/6946666.html 

  • 相关阅读:
    OpenRisc-52-run openrisc&orpmon on ml501 board
    PHP之APC缓存详细介绍(转)
    ios 使用GCD 多线程 教程
    poj2454
    尝鲜delphi开发android/ios_环境搭建
    HDU 3308 线段树 最长连续上升子序列 单点更新 区间查询
    jQuery 表格排序插件 Tablesorter 使用
    Oracle 常见错误
    安卓开发44:解决 INSTALL_FAILED_UID_CHANGED 等问题
    Java的native方法
  • 原文地址:https://www.cnblogs.com/xuchunlin/p/6946666.html
Copyright © 2011-2022 走看看