天天看点

datetime,time

datetime模块中有如下几个重要类:datetime,date,time,tzinfo,timedelta。

time模块包含struct_time类,一些常量和函数,time模块里的函数大部分调用了平台的C函数,因此需要注意平台相关性。

struct_time即时间元组,很多Python函数用一个元组装起来的9组数字处理时间,我们只要将浮点数传递给如localtime之类的函数即可得到时间元组。

通过查看资料我们可以发现datetime类和time模块中的time有很多类似的地方,因此可以把datetime看作time的加强版。

时间格式化和字符串转时间

在time和datetime中函数名和用法是相同的。

  1. strftime是时间格式为字符串的函数

    time或datime.strftime(format[, t])

  2. strptime是时间格式化字符串转时间的函数

    datetime.strptime(date_string, format)返回datetime,而time.strptime(string[, format])返回struct_time。

    datetime.strptime等价于datetime(*(time.strptime(date_string, format)[0:6]))

时间加减

在datetime中,我们使用timedelta进行时间加减,计算日期差值。

时区

time中有2个属性字段来表示时区信息time.timezone和time.tzname

datetime模块将时区信息封装到了tzinfo类中

时间戳转换

  1. time

    1.1 返回时间元组: 只要将浮点数传递给如localtime函数。

    1.2 返回当前时间的时间戳: time.time( )

    1.3 接受时间元组并返回时间戳: time.mktime(tupletime)

  2. datetime

    2.1 返回当前系统时间:datetime.now()

其他

time.sleep(secs)

推迟调用线程的运行,secs指秒数。

参考:

python datetime模块

https://www.runoob.com/python3/python3-date-time.html

https://docs.python.org/3.7/library/datetime.html

python time 模块

https://docs.python.org/3.7/library/time.html#module-time

CTP

继续阅读