python3中time模块的用法及说明

简介: python中,导入time模块使用的命令是import time可以使用以下命令查看time模块内置的能够使用的方法:dir(time)可以使用以下命令查看time模块中每个内置方法的说明:help(time.time_method)比如time模块下有一个time.time的方法,现在我想查看这个方法的官方文档,就可以使用这样的命令:help(time.time)时间的表示形式:在python中,通常有三种方式来表示时间:时间戳,元组(结构化时间,struct_time),格式化的时间字符串。

python中,导入time模块使用的命令是

import time

可以使用以下命令查看time模块内置的能够使用的方法:

dir(time)

可以使用以下命令查看time模块中每个内置方法的说明:

help(time.time_method)

比如time模块下有一个time.time的方法,现在我想查看这个方法的官方文档,就可以使用这样的命令:

help(time.time)

时间的表示形式:

在python中,通常有三种方式来表示时间:时间戳,元组(结构化时间,struct_time),格式化的时间字符串。

时间戳(timestamp):通常来说,时间戳表示从1970年1月1日00:00:00开始按秒计算的偏移量,它的值是float类型
格式化的时间字符串(Format String):‘2017-06-20’
结构化时间(struct_time):struct_time元组共有9个元素:(年,月,日,时,分,秒,一年中的第几周,一年中的第几天等)

time模块中内置的常用的方法:

asctime

接受时间元组并返回一个可读的形式"Tue May 30 17:17:30 2017"(2017年5月30日周二17时17分30秒)的24个字符的字符串
Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
When the time tuple is not present, current time as returned by localtime()
is used.
>>> time.asctime()
'Thu Jun 22 19:27:19 2017'

ctime

作用相当于asctime(localtime(secs)),未给参数相当于asctime()
ctime(seconds) -> string
Convert a time in seconds since the Epoch to a string in local time.
This is equivalent to asctime(localtime(seconds)). When the time tuple is
not present, current time as returned by localtime() is used.
>>> time.ctime()
'Thu Jun 22 19:34:35 2017'

gmtime

接收时间辍(1970纪元年后经过的浮点秒数)并返回格林威治天文时间下的时间元组t(t.tm_isdst始终为0)
gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
                       tm_sec, tm_wday, tm_yday, tm_isdst)
Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
GMT).  When 'seconds' is not passed in, convert the current time instead.
If the platform supports the tm_gmtoff and tm_zone, they are available as
attributes only.
>>> time.gmtime()
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=22, tm_hour=11, tm_min=35, tm_sec=12, tm_wday=3, tm_yday=173, tm_isdst=0)

localtime

接收时间辍(1970纪元年后经过的浮点秒数)并返回当地时间下的时间元组t(t.tm_isdst可取为0或1,取决于当地当时是不是夏令时)
localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
                          tm_sec,tm_wday,tm_yday,tm_isdst)
Convert seconds since the Epoch to a time tuple expressing local time.
When 'seconds' is not passed in, convert the current time instead.
>>> time.localtime()
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=22, tm_hour=19, tm_min=35, tm_sec=35, tm_wday=3, tm_yday=173, tm_isdst=0)

mktime

接受时间元组并返回时间辍(1970纪元年后经过的浮点秒数)
mktime(tuple) -> floating point number
Convert a time tuple in local time to seconds since the Epoch.
Note that mktime(gmtime(0)) will not generally return zero for most
time zones; instead the returned value will either be equal to that
of the timezone or altzone attributes on the time module.
>>> time.mktime(time.localtime())
1498131370.0

sleep

推迟调用线程的运行,secs的单位是秒
Delay execution for a given number of seconds.  The argument may be
a floating point number for subsecond precision.

strftime

把一个代表时间的元组或者struct_time(如由time.localtime()和time.gmtime()返回)转化为格式化的时间字符串.如果t未指定,将传入time.localtime(),如果元组中任命一个元素越界,将会抛出ValueError异常
strftime(format[, tuple]) -> string
Convert a time tuple to a string according to a format specification.
See the library reference manual for formatting codes. When the time tuple
is not present, current time as returned by localtime() is used.

    Commonly used format codes:
    
    %Y  Year with century as a decimal number.===>完整的年份
    %m  Month as a decimal number [01,12].===>月份(01-12)
    %d  Day of the month as a decimal number [01,31].===>一个月中的第几天(01-31)
    %H  Hour (24-hour clock) as a decimal number [00,23].===>一天中的第几个小时(24小时制,00-23)
    %M  Minute as a decimal number [00,59].===>分钟数(00-59)
    %S  Second as a decimal number [00,61].===>秒(01-61)
    %z  Time zone offset from UTC.===>用+HHMM或者-HHMM表示距离格林威治的时区偏移(H代表十进制的小时数,M代表十进制的分钟数)
    %a  Locale's abbreviated weekday name.===>本地(local)简化星期名称
    %A  Locale's full weekday name.===>本地完整星期名称
    %b  Locale's abbreviated month name.===>本地简化月份名称
    %B  Locale's full month name.===>本地完整月份名称
    %c  Locale's appropriate date and time representation.===>本地相应的日期和时间表示
    %I  Hour (12-hour clock) as a decimal number [01,12].===>一天中的第几个小时(12小时制,01-12)
    %p  Locale's equivalent of either AM or PM.===>本地am或者pm的相应符
>>> time.strftime("%Y-%m-%d")
'2017-06-22'
>>> time.strftime("%Y-%m-%d %H-%H-%S")
'2017-06-22 19-19-28'

strptime

把一个格式化时间字符串转化为struct_time,实际上它和strftie()是逆操作
strptime(string, format) -> struct_time
Parse a string to a time tuple according to a format specification.
See the library reference manual for formatting codes (same as
strftime()).
>>> time.strptime("2017-06-21","%Y-%m-%d")
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=21, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=172, tm_isdst=-1)
>>> time.strptime("2017-06-21 12-34-45","%Y-%m-%d %H-%M-%S")
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=21, tm_hour=12, tm_min=34, tm_sec=45, tm_wday=2, tm_yday=172, tm_isdst=-1)

struct_time

把一个时间转换成结构化时间
The time value as returned by gmtime(), localtime(), and strptime(), and
accepted by asctime(), mktime() and strftime().  May be considered as a
sequence of 9 integers.
>>> time.struct_time(time.localtime())
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=22, tm_hour=19, tm_min=42, tm_sec=7, tm_wday=3, tm_yday=173, tm_isdst=0)

time

返回当前时间的时间戳(1970元年后的浮点秒数
Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.
>>> time.time()
1498131760.7711384
>>> time.time()
1498131764.7621822

几种时间形式的转换

1.把时间戳转换成结构化时间,使用的是time.localtime或time.gmtime命令。

>>> t1=time.time()
>>> print(t1)
1498132526.8227696
>>> t2=time.localtime(t1)
>>> print(t2)
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=22, tm_hour=19, tm_min=55, tm_sec=26, tm_wday=3, tm_yday=173, tm_isdst=0)

2.把结构化时间转换成时间戳,使用time.mktime命令
>>> t3=time.struct_time(time.localtime())
>>> print(t3)
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=22, tm_hour=19, tm_min=58, tm_sec=29, tm_wday=3, tm_yday=173, tm_isdst=0)
>>> t4=time.mktime(t3)
>>> print(t4)
1498132709.0

3.把结构化时间转换成时间字符串,使用time.strftime命令
>>> t1=time.localtime()
>>> print(t1)
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=22, tm_hour=20, tm_min=0, tm_sec=37, tm_wday=3, tm_yday=173, tm_isdst=0)
>>> t2=time.strftime("%Y-%m-%d",t1)
>>> print(t2)
2017-06-22
4.把字符串时间转换成结构化时间,使用的是time.strptime命令
>>> t1="2017-05-20 08:08:10"
>>> print(t1)
2017-05-20 08:08:10
>>> t2=time.strptime(t1,"%Y-%m-%d %H:%M:%S")
>>> print(t2)
time.struct_time(tm_year=2017, tm_mon=5, tm_mday=20, tm_hour=8, tm_min=8, tm_sec=10, tm_wday=5, tm_yday=140, tm_isdst=-1)

例子:
假如我有一个时间字符串,然后想得到这个时间之后3天的时间字符串,可以使用如下的命令:

import time
time1 = "2017-05-20"
#把时间字符串转换为时间戳,然后加上3天时间的秒数
time2 = time.mktime(time.strptime(time1,"%Y-%m-%d"))+3 * 24 * 3600
#把转换后的时间戳再转换成时间字符串
time3 = time.strftime("%Y-%m-%d", time.localtime(time2))
print(time3)
目录
相关文章
|
5月前
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
691 7
|
5月前
|
监控 安全 程序员
Python日志模块配置:从print到logging的优雅升级指南
从 `print` 到 `logging` 是 Python 开发的必经之路。`print` 调试简单却难维护,日志混乱、无法分级、缺乏上下文;而 `logging` 支持级别控制、多输出、结构化记录,助力项目可维护性升级。本文详解痛点、优势、迁移方案与最佳实践,助你构建专业日志系统,让程序“有记忆”。
442 0
|
5月前
|
机器学习/深度学习 PyTorch 算法框架/工具
python torch基础用法
本教程系统讲解PyTorch基础,涵盖张量操作、自动求导、神经网络构建、训练流程、GPU加速及模型保存等核心内容,结合代码实例帮助初学者快速掌握深度学习开发基础,是入门PyTorch的实用指南。
726 6
|
5月前
|
JSON 算法 API
Python中的json模块:从基础到进阶的实用指南
本文深入解析Python内置json模块的使用,涵盖序列化与反序列化核心函数、参数配置、中文处理、自定义对象转换及异常处理,并介绍性能优化与第三方库扩展,助你高效实现JSON数据交互。(238字)
536 4
|
5月前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
543 0
|
5月前
|
XML JSON 数据处理
超越JSON:Python结构化数据处理模块全解析
本文深入解析Python中12个核心数据处理模块,涵盖csv、pandas、pickle、shelve、struct、configparser、xml、numpy、array、sqlite3和msgpack,覆盖表格处理、序列化、配置管理、科学计算等六大场景,结合真实案例与决策树,助你高效应对各类数据挑战。(238字)
654 0
|
6月前
|
安全 大数据 程序员
Python operator模块的methodcaller:一行代码搞定对象方法调用的黑科技
`operator.methodcaller`是Python中处理对象方法调用的高效工具,替代冗长Lambda,提升代码可读性与性能。适用于数据过滤、排序、转换等场景,支持参数传递与链式调用,是函数式编程的隐藏利器。
215 4
|
7月前
|
Go 调度 Python
Golang协程和Python协程用法上的那些“不一样”
本文对比了 Python 和 Go 语言中协程的区别,重点分析了调度机制和执行方式的不同。Go 的协程(goroutine)由运行时自动调度,启动后立即执行;而 Python 协程需通过 await 显式调度,依赖事件循环。文中通过代码示例展示了两种协程的实际运行效果。
311 7
|
6月前
|
存储 数据库 开发者
Python SQLite模块:轻量级数据库的实战指南
本文深入讲解Python内置sqlite3模块的实战应用,涵盖数据库连接、CRUD操作、事务管理、性能优化及高级特性,结合完整案例,助你快速掌握SQLite在小型项目中的高效使用,是Python开发者必备的轻量级数据库指南。
540 0
|
7月前
|
存储 安全 数据处理
Python 内置模块 collections 详解
`collections` 是 Python 内置模块,提供多种高效数据类型,如 `namedtuple`、`deque`、`Counter` 等,帮助开发者优化数据处理流程,提升代码可读性与性能,适用于复杂数据结构管理与高效操作场景。
467 0

推荐镜像

更多