zoukankan      html  css  js  c++  java
  • 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-基础-时间日期处理小结

  • 相关阅读:
    自己用的vim插件
    关于利用python进行验证码识别的一些想法
    看看黑客如何破解验证码机制
    不懂技术的人不要对懂技术的人说这很容易实现
    4个mysql客户端工具的比较
    GB2312,GBK和UTF-8的区别
    Windows下用Python你会几种copy文件的方法?
    python3.4连接mysql数据库的方法
    python3操作mysql教程
    python win32com
  • 原文地址:https://www.cnblogs.com/gattaca/p/7285550.html
Copyright © 2011-2022 走看看