zoukankan      html  css  js  c++  java
  • python datetime模块用法

    1. 创建naive(无时区信息)的datetime对象

    import datetime  
     
    dt_utc = datetime.datetime.utcnow()
    
    dt_utc # datetime.datetime(2019, 2, 1, 10, 53, 34, 145034)
    
    dt_utc.tzinfo # None 
    
    dt_local = datetime.datetime.now()
    
    dt_local.tzinfo # None 
    
    # tzinfo为None的datetime对象is naive(不知道怎么翻译好。。。)
    
    # tzinfo为tzinfo对象的None的datetime对象is aware。
    
    # 只有都为naive或者都为aware才可以相互比较
    

    2. 创建的aware(有时区信息)的datetime对象

    import datetime  
     
    dt_utc = datetime.datetime.utcnow()
    
    dt_utc_aware = dt.replace(tzinfo=datetime.timezone.utc)
    
    dt_utc_aware.tzinfo # datetime.timezone.utc
    
    dt_local = datetime.datetime.now()
    
    dt_local_aware = dt_local.replace(tzinfo=datetime.tzinfo(datetime.timedelta(hours=8)))
    

    3. datetime对象的时区转换

    import datetime  
     
    dt_utc = datetime.datetime.utcnow()
    
    dt_utc_aware = dt.replace(tzinfo=datetime.timezone.utc)
    
    dt_utc_aware.tzinfo # datetime.timezone.utc
    
    dt_local_aware = dt_utc_aware.astimezone(datetime.timezone(datetime.timedelta(hours=8))) # 转为北京时间
    

    4. datetime对象和时间戳互转

    import datetime  
     
    import time
    
    stamp = time.time() # 获取时间戳
    
    dt_utc = datetime.datetime.utcfromtimestamp(stamp) # 转为datetime
    
    # datetime.datetime(2019, 2, 1, 12, 52, 59, 268168)
    
    dt_local = datetime.datetime.fromtimestamp(stamp)
    
    # datetime.datetime(2019, 2, 1, 20, 52, 59, 268168)
    
    stp = dt_utc.timestamp() # 转为时间戳,时间戳唯一,不因时区变化
    

    4. datetime对象和date对象互转

    import datetime  
    
    d_local = datetime.date.today() # 获取date
    
    dt_utc = datetime.datetime.fromordinal(d_local.toordinal()) # 转为datetime
    
    # datetime.datetime(2019, 2, 1, 0, 0)
    
    d_ = dt_utc.date() # 转为date
    
    # datetime.date(2019, 2, 1)
  • 相关阅读:
    php 基础------数组过滤
    js或者jq 使用cookie 时在谷歌浏览器不好使
    css3 -阻止元素成为鼠标事件目标 pointer-events
    CSS3-----transform 转换
    css3---过渡
    css3动画----animation
    移动端尺寸适配--媒体查询
    工作一年总结
    关于Jquery.Data()和HTML标签的data-*属性
    android shape
  • 原文地址:https://www.cnblogs.com/lyg-blog/p/10347033.html
Copyright © 2011-2022 走看看