• python模块之time and datetime


    time

    # python3
    # coding = utf-8
    
    import time
    
    timestamp = time.time()
    print('timestamp:%s, type: %s' % (timestamp, type(timestamp)))
    
    # time.localtime() 默认使用 time.time()
    localtime = time.localtime()
    print('localtime:', localtime)
    print('current hour is:', localtime[3])
    print('current hour is:', localtime.tm_hour)
    
    # time.asctime() 默认使用 time.localtime()
    print('localtime_readable:', time.asctime())
    # time.ctime() 默认使用 time.time()
    print('localtime_readable:', time.ctime())
    
    # time.strftime 默认使用 time.localtime()
    print('localtime_formatted:', time.strftime('%Y-%m-%d %H:%M:%S'))
    
    # 将格式字符串转换为时间戳
    test_str = '2017-08-26 12:12:12'
    test_timestamp = time.mktime(time.strptime(test_str, '%Y-%m-%d %H:%M:%S'))
    print('test_timestamp:', test_timestamp)

    输出:

    timestamp:1505887820.714079, type: <class 'float'>
    localtime: time.struct_time(tm_year=2017, tm_mon=9, tm_mday=20, tm_hour=14, tm_min=10, tm_sec=20, tm_wday=2, tm_yday=263, tm_isdst=0)
    current hour is: 14
    current hour is: 14
    localtime_readable: Wed Sep 20 14:10:20 2017
    localtime_readable: Wed Sep 20 14:10:20 2017
    localtime_formatted: 2017-09-20 14:10:20
    test_timestamp: 1503720732.0

    datetime

    # python3
    # coding = utf-8
    
    import datetime
    
    now = datetime.datetime.now()
    print('now:%s, type: %s' % (now, type(now)))
    print('now_replace',now.replace(hour=0, minute=0, second=0))
    print('now.day:', now.day)
    print('now_formatter:', now.strftime('%Y-%m-%d'))
    print('now_timestamp:', now.timestamp())
    print('old_time:', datetime.datetime(2015, 4, 29, 12, 20))
    print('midnight:', datetime.datetime.combine(datetime.date.today(), datetime.time.min))

    输出:

    now:2017-09-20 14:11:07.533828, type: <class 'datetime.datetime'>
    now_replace 2017-09-20 00:00:00.533828
    now.day: 20
    now_formatter: 2017-09-20
    now_timestamp: 1505887867.533828
    old_time: 2015-04-29 12:20:00
    midnight: 2017-09-20 00:00:00

    参考资料:

    PYTHON-基础-时间日期处理小结

  • 相关阅读:
    二项分布 正太分布 关系 隶莫佛-拉普拉斯定理的推广 列维-林德伯格定理
    lint (software)
    eslint
    Lazy freeing of keys 对数据的额异步 同步操作 Redis 4.0 微信小程序
    XML-RPC JSON-RPC RPC是实现思路
    Multitier architecture
    Messaging Patterns for Event-Driven Microservices
    替换模板视频图片的原理
    Understanding When to use RabbitMQ or Apache Kafka Kafka RabbitMQ 性能对比
    RabbitMQ Connector
  • 原文地址:https://www.cnblogs.com/gattaca/p/7285550.html
Copyright © 2020-2023  润新知