zoukankan      html  css  js  c++  java
  • 时间相关的模块

    格式化好的时间 2020-05-16 18:10:20
    时间戳 156854124141 从unix 元年,从计算机发明的那一年,到现在发生了多少秒,没过一秒加1
    计算时间 用时间戳比较方便

    获取时间
    print(time.time()) #获取当前时间的时间戳
    print(time.strftime('%Y-%m-%d %H:%M:%S')) #获取当前时间的格式化时间,要指定格式
    print(time.strftime('%Y-%m'))
    print(time.strftime('%Y-%m-%d'))
    print(time.strftime('%Y/%m/%d'))
     
    运行结果:
    1589625355.8514764
    2020-05-16 18:35:55
    2020-05
    2020-05-16
    2020/05/16
    
    时间的互相转换,格式化好时间和时间戳之间不能直接转换,需要通过时间元组

     1.时间戳转格式化时间

    import time,datetime
    result=time.localtime(1589617159.785086) #把时间戳转换为时间元组
    print(result)
    print(time.strftime('%Y/%m/%d',result)) #将时间元组转为格式化的时间,可以指定格式
    print(time.strftime('%Y-%m-%d %H:%M:%S',result))
    
    
    运行结果:
    time.struct_time(tm_year=2020, tm_mon=5, tm_mday=16, tm_hour=16, tm_min=19, tm_sec=19, tm_wday=5, tm_yday=137, tm_isdst=0)
    2020/05/16
    2020-05-16 16:19:19
    

     2.格式化时间转时间戳

    import time,datetime
    result=time.strptime('2020-05-16 16:19:19','%Y-%m-%d %H:%M:%S') #把时间戳转换为时间元组
    print(time.mktime(result)) #将元组转成时间戳
    
    运行结果:
    1589617159.0
    

    sleep等待多久之后再执行下面的代码  

    # time.sleep(10)
    # print('等待10s后再运行')

    以下是实现时间转换的函数:

    import time,datetime
    def str_to_timezone(str=None,format="%Y-%m-%d %H:%M:%S"):
        #这个函数是格式化好的时间转时间戳的,如果不传参数默认返回当前时间戳
        if str:
            time_tuple = time.strptime(str,format)
            result = time.mktime(time_tuple)
        else:
            result = time.time()
        return int(result)
    
    print(str_to_timezone('2020-05-16 16:19:19'))
    
    
    def timezone_to_str(timezone=None,format="%Y-%m-%d %H:%M:%S"):
        '''这个函数是时间戳转格式化好的时间,如果不传参数,默认返回当前时间'''
        if timezone:
            time_tuple = time.localtime(timezone)
            result = time.strftime(format,time_tuple)
        else:
            result = time.strftime(format)
        return result
    
    print(timezone_to_str(1589617159))
    
    运行结果:
    1589617159
    2020-05-16 16:19:19
    

      

  • 相关阅读:
    开发Django项目01
    本地安装python2.x和python3.x双版本之后怎么使用pip
    python3.x并发编程
    centos6.8安装JDK1.8教程
    yum安装MySQL指定版本
    python爬虫爬取get请求的页面数据代码样例
    python网络爬虫学习笔记
    python通过get方式,post方式发送http请求和接收http响应-urllib urllib2
    CentOS7.5安装python-pip报Error: Nothing to do解决方法
    文件操作
  • 原文地址:https://www.cnblogs.com/MLing/p/12901705.html
Copyright © 2011-2022 走看看