签到成功

知道了

CNDBA社区CNDBA社区

Python第14天--datetime&time

2021-11-07 09:24 852 0 原创 Python
作者: hbhe0316

datetime模块
datetime 模块是 Python 内置的功能模块,它可以实现对日期的算数运算,以指定的方式格式化日期。datetime 模块内含有一个同名的 datetime 类,该类中包含多个操作日期的函数,例如:datetime.now()、datetime.fromtimestamp()、datetime.timedelta()等,下面逐一举例说明。http://www.cndba.cn/hbhe0316/article/5047http://www.cndba.cn/hbhe0316/article/5047

1.datetime()构造函数
datetime 类提供了一个now()的方法可以获取当前日期和时间,还提供了带参数的构造函数datetime(),可以通过传入特定的数字返回不同的datetime 对象。例如:

#当前日期和时间
print(datetime.datetime.now())

#获取指定时间
datetest = datetime.datetime(2021,11,7,9,5,0)
print(datetest)

#获取日期的年月日时分秒
print(str(datetest.year)+"-"+str(datetest.month)+"-"+str(datetest.day)+" "+str(datetest.hour)+":"+str(datetest.minute)+":"+str(datetest.second))

http://www.cndba.cn/hbhe0316/article/5047http://www.cndba.cn/hbhe0316/article/5047

2.time模块
与 datetime 模块有所不同,time 模块主要功能是读取系统时钟的当前时间。其中,time.time() 和 time.sleep() 是两个最常用的模块。

time()函数
time.time() 函数返回的值是带小数点的,它表示从 Unix 纪元(1970年1月1日0点)到执行代码那一刻所经历的时间的秒数,这个数字称为UNIX纪元时间戳。例如:http://www.cndba.cn/hbhe0316/article/5047

http://www.cndba.cn/hbhe0316/article/5047

import time
print ("当前时间戳为:", time.time())

http://www.cndba.cn/hbhe0316/article/5047

3.sleep()函数
如果需要让程序暂停一下,可以使用time.sleep()函数。sleep()函数有个参数,表示需要暂停的秒数。例如:http://www.cndba.cn/hbhe0316/article/5047

http://www.cndba.cn/hbhe0316/article/5047
http://www.cndba.cn/hbhe0316/article/5047

import time
for i in range(2):
    print('one')
    print(time.time())
    time.sleep(1)
    print('two')
    print(time.time())
    time.sleep(1)
print('运行完成')

版权声明:本文为博主原创文章,未经博主允许不得转载。

Python

用户评论
* 以下用户言论只代表其个人观点,不代表CNDBA社区的观点或立场
hbhe0316

hbhe0316

关注

1.只有承认无知,才能装下新的东西; 2.进步来自一点点滴滴的积累; 3.广博让你更优秀,而专业让你无法替代; 4.挫折和失败能够转换为一种财富。

  • 889
    原创
  • 1
    翻译
  • 13
    转载
  • 24
    评论
  • 访问:1038383次
  • 积分:1523
  • 等级:核心会员
  • 排名:第6名
精华文章
    最新问题
    查看更多+
    热门文章
      热门用户
      推荐用户
        Copyright © 2016 All Rights Reserved. Powered by CNDBA · 皖ICP备2022006297号-1·

        QQ交流群

        注册联系QQ