zoukankan      html  css  js  c++  java
  • Python 时间戳/字符串/时间 转换

    概要
    平时对于时间的处理经常使用python的time和datetime模块,但是用来多次还是对其中的时间戳,字符串和时间转换应用的不太熟练,时间长了不使用就理不清楚,为此整理成文。

    视图
    时间戳,时间,字符串之间的关系整理如下图:

     


    示例
    时间戳和时间的转换
    import time


    if __name__ == "__main__":
    # 时间戳: time.time() 返回当前时间戳
    seconds = time.time()

    # time.localtime()将时间戳转换为struct_time
    s_time = time.localtime(seconds)
    print s_time

    # time.mktime()将struct_time转换为时间戳
    print time.mktime(s_time)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    # 输出 struct time: 包含年,月,日,小时,分钟,秒等
    time.struct_time(tm_year=2018, tm_mon=8, tm_mday=11, tm_hour=17, tm_min=31, tm_sec=57, tm_wday=5, tm_yday=223, tm_isdst=0)

    # 时间戳
    1533980060.0
    1
    2
    3
    4
    5
    时间和字符串之间的转换
    import time


    if __name__ == "__main__":
    # time.strptime() 将字符串转换为struct_time
    # %Y: 年
    # %m: 月
    # %d: 日
    # %H: 时, %M:分, %S:秒, 更多详细需参考python time模块文档
    s_time = time.strptime("2018-08-07", "%Y-%m-%d")
    print s_time

    # time.strftime()将struct_time转换为字符串
    print time.strftime("%Y-%m-%d %H:%M:%S", s_time)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    # 输出
    time.struct_time(tm_year=2018, tm_mon=8, tm_mday=7, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=219, tm_isdst=-1)

    2018-08-07 00:00:00
    1
    2
    3
    4
    时间戳和字符串之间的转换

    时间戳和字符串之间没有直接的转换方法,需要借助struct_time实现转换

    import time


    if __name__ == "__main__":
    # 时间戳
    seconds = time.time()

    # 时间戳转换为字符串
    print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds))

    # 字符串转换为时间戳
    print time.mktime(time.strptime("2018-08-07", "%Y-%m-%d"))
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    # 输出
    2018-08-11 17:47:43

    1533571200.0
    ---------------------
    作者:回眸郎
    来源:CSDN
    原文:https://blog.csdn.net/ymaini/article/details/81589157
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    iOS 苹果开发证书失效的解决方案(Failed to locate or generate matching signing assets)
    iOS NSArray数组过滤
    App Store2016年最新审核规则
    iOS 根据字符串数目,自定义Label等控件的高度
    iOS 证书Bug The identity used to sign the executable is no longer valid 解决方案
    Entity FrameWork 增删查改的本质
    EF容器---代理类对象
    Entity FrameWork 延迟加载本质(二)
    Entity FrameWork 延迟加载的本质(一)
    Entity FrameWork 增删查改
  • 原文地址:https://www.cnblogs.com/linwenbin/p/10905341.html
Copyright © 2011-2022 走看看