• python中与time模块和datetime模块相关操作


    使用time模块计时程序运行时长

    import
    time time_start = time.time() #程序主体部分 time_end = time.time() print('总耗时: ', time_end-time_start, '')

     

    python 日期、时间、字符串相互转换

    参考https://www.cnblogs.com/huhu-xiaomaomi/p/10338472.html

    在python中,日期类型date和日期时间类型dateTime是不能比较的。

    (1)如果要比较,可以将dateTime转换为date,date不能直接转换为dateTime

    import datetime
    dateTime_p = datetime.datetime.now()  
    date_p = dateTime_p.date() 
    print(dateTime_p) #2019-01-30 15:17:46.573139
    print(date_p) #2019-01-30

    (2)日期类型date转换为字符串str

    #!/usr/bin/env python3
    import datetime
    date_p = datetime.datetime.now().date()
    str_p = str(date_p)
    print(date_p,type(date_p)) #2019-01-30 <class 'datetime.date'>
    print(str_p,type(str_p)) #2019-01-30 <class 'str'>

    (3)字符串类型str转换为dateTime类型

    import datetime
    str_p = '2019-01-30 15:29:08'
    dateTime_p = datetime.datetime.strptime(str_p,'%Y-%m-%d %H:%M:%S')
    print(dateTime_p) # 2019-01-30 15:29:08

    >>> a='2019-08-15 16:01:20'
    >>> a
    '2019-08-15 16:01:20'
    >>> import datetime
    >>> datetime.datetime.strptime(a,'%Y-%m-%d %H:%M:%S')
    datetime.datetime(2019, 8, 15, 16, 1, 20)
    >>> b= datetime.datetime.strptime(a,'%Y-%m-%d %H:%M:%S')
    >>> b
    datetime.datetime(2019, 8, 15, 16, 1, 20)
    >>> print(b)
    2019-08-15 16:01:20
    >>>

    (4)dateTime类型转为str类型

      这个地方我也不太理解,为什么指定格式无效

    import datetime
    dateTime_p = datetime.datetime.now()
    str_p = datetime.datetime.strftime(dateTime_p,'%Y-%m-%d')
    print(dateTime_p) # 2019-01-30 15:36:19.415157

    (5)字符串类型str转换为date类型

    #!/usr/bin/env python3
    import datetime
    str_p = '2019-01-30'
    date_p = datetime.datetime.strptime(str_p,'%Y-%m-%d').date()
    print(date_p,type(date_p)) # 2019-01-30 <class 'datetime.date'>

    另外dateTime类型和date类型可以直接做加1减1这种操作

    #!/usr/bin/env python3
    import datetime
    # today = datetime.datetime.today()
    today = datetime.datetime.today().date()
    yestoday = today + datetime.timedelta(days=-1)
    tomorrow = today + datetime.timedelta(days=1)
    print(today) # 2019-01-30
    print(yestoday)# 2019-01-29
    print(tomorrow)# 2019-01-31
  • 相关阅读:
    Regular Expression Basic
    Getting http address from text file by awk script
    日报、周报,项目进度汇报有意义吗?
    目不转睛地盯着电脑屏幕,认真找Bug的你
    这组朋友圈,得罪了半个互联网圈!
    2021年,让你看透世界的8个底层逻辑
    再见,胡阿姨!再见,共享单车!
    @所有人,2021新年快乐,每个人都了不起!
    为了实现而工程,大道至简第五章读后感
    Java第四次上课博文动手动脑
  • 原文地址:https://www.cnblogs.com/feng-hao/p/11328154.html
Copyright © 2020-2023  润新知