zoukankan      html  css  js  c++  java
  • Python 中时间与时间戳转换

    首先,时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总毫秒数。通俗的讲, 时间戳是一份能够表示一份数据在一个特定时间点已经存在的完整的可验证的数据。

    1.获取时间戳

    import time
    t = time.time()
     
    print(t)                        #原始时间数据
    print(int(t))                   #秒级时间戳
    print(int(t * 1000))            #毫秒级时间戳
    print(int(t * 1000000))         #微秒级时间戳
     
     
     
    返回结果
     
    1585806944.976753
    1585806944
    1585806944976
    1585806944976753

    2.获取当前时间

    import datetime
     
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    now_ms = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') 
    print(now)
    print(now_ms)
     
    返回结果
     
    2020-04-02 13:58:51
    2020-04-02 13:58:51.294867

    3.将日期转为秒级时间戳

    dt = '2020-04-02 13:58:51'
    ts = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
    print(ts)
     
    返回
    1585807131

    4.时间戳转日期

    ts = 1585807131
    dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts))
    print(dt)
     
    返回
    2020-04-02 13:58:51

    5.日期格式转换

    dt = '2020-04-02 13:58:51'
    dt_new = datetime.datetime.strptime(dt, '%Y-%m-%d %H:%M:%S').strftime('%m/%d/%Y %H:%M')
    print(dt_new)
     
    返回
    04/02/2020 13:58

    6.转结构体时间

    ta_dt = time.strptime("2020-04-02 13:58:51", '%Y-%m-%d %H:%M:%S')
    ta_ms = time.localtime(1585807131)
    print(ta_dt)
    print(ta_ms)
     
    返回
    time.struct_time(tm_year=2020, tm_mon=4, tm_mday=2, tm_hour=13, tm_min=58, tm_sec=51, tm_wday=3, tm_yday=93, tm_isdst=-1)
    time.struct_time(tm_year=2020, tm_mon=4, tm_mday=2, tm_hour=13, tm_min=58, tm_sec=51, tm_wday=3, tm_yday=93, tm_isdst=0)

    ————————————————
    版权声明:本文为CSDN博主「YuG819」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/qq_31033037/article/details/105268417

    你有什么心态,就有什么样的人生。管不好自己的心态,注定你就是个弱者。
  • 相关阅读:
    [luogu p1996] 约瑟夫问题
    [luogu p1098] 字符串的展开
    [luogu p1035] 级数求和
    [luogu p1004] 方格取数
    [luogu p3383]【模板】线性筛素数
    [luogu p1223] 排队接水
    [luogu p1002] 过河卒
    [luogu p1001] A+B Problem
    Java BIO/NIO(Non-blocking I/O)详解
    Linux页框&伙伴算法以及slab机制
  • 原文地址:https://www.cnblogs.com/LQZ888/p/12626822.html
Copyright © 2011-2022 走看看