Python学习之time模块的基本使用

前言

在我们学习的过程中,肯定会用到各种各样的模块。所以今天我们从time模块开始学习

首先我们在使用某个模块的时候,肯定要先导入这个模块

import time

而当我们想看看这个模块是干什么的,我们可以使用help函数来看

print(help(time)) # 打印帮助信息
"E:\Program Files (x86)\python_3.8\python.exe" D:/Application/pycharm_works/_1/test/python模块之time模块.py
Help on built-in module time:

NAME
 time - This module provides various functions to manipulate time values.

DESCRIPTION
 There are two standard representations of time. One is the number
 of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer
 or a floating point number (to represent fractions of seconds).
 The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
 The actual value can be retrieved by calling gmtime(0).

 The other representation is a tuple of 9 integers giving local time.
 The tuple items are:
  year (including century, e.g. 1998)
  month (1-12)
  day (1-31)
  hours (0-23)
  minutes (0-59)
  seconds (0-59)
  weekday (0-6, Monday is 0)
  Julian day (day in the year, 1-366)
  DST (Daylight Savings Time) flag (-1, 0 or 1)
 If the DST flag is 0, the time is given in the regular time zone;
 if it is 1, the time is given in the DST time zone;
 if it is -1, mktime() should guess based on the date and time.

CLASSES
 builtins.tuple(builtins.object)
  struct_time

 class struct_time(builtins.tuple)
  | struct_time(iterable=(), /)
  |
  | 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.
  |
  | Note that several fields' values are not the same as those defined by
  | the C language standard for struct tm. For example, the value of the
  | field tm_year is the actual year, not year - 1900. See individual
  | fields' descriptions for details.
  |
  | Method resolution order:
  |  struct_time
  |  builtins.tuple
  |  builtins.object
  |
  | Methods defined here:
  |
  | __reduce__(...)
  |  Helper for pickle.
  |
  | __repr__(self, /)
  |  Return repr(self).
  |
  | ----------------------------------------------------------------------
  | Static methods defined here:
  |
  | __new__(*args, **kwargs) from builtins.type
  |  Create and return a new object. See help(type) for accurate signature.
  |
  | ----------------------------------------------------------------------
  | Data descriptors defined here:
  |
  | tm_gmtoff
  |  offset from UTC in seconds
  |
  | tm_hour
  |  hours, range [0, 23]
  |
  | tm_isdst
  |  1 if summer time is in effect, 0 if not, and -1 if unknown
  |
  | tm_mday
  |  day of month, range [1, 31]
  |
  | tm_min
  |  minutes, range [0, 59]
  |
  | tm_mon
  |  month of year, range [1, 12]
  |
  | tm_sec
  |  seconds, range [0, 61])
  |
  | tm_wday
  |  day of week, range [0, 6], Monday is 0
  |
  | tm_yday
  |  day of year, range [1, 366]
  |
  | tm_year
  |  year, for example, 1993
  |
  | tm_zone
  |  abbreviation of timezone name
  |
  | ----------------------------------------------------------------------
  | Data and other attributes defined here:
  |
  | n_fields = 11
  |
  | n_sequence_fields = 9
  |
  | n_unnamed_fields = 0
  |
  | ----------------------------------------------------------------------
  | Methods inherited from builtins.tuple:
  |
  | __add__(self, value, /)
  |  Return self+value.
  |
  | __contains__(self, key, /)
  |  Return key in self.
  |
  | __eq__(self, value, /)
  |  Return self==value.
  |
  | __ge__(self, value, /)
  |  Return self>=value.
  |
  | __getattribute__(self, name, /)
  |  Return getattr(self, name).
  |
  | __getitem__(self, key, /)
  |  Return self[key].
  |
  | __getnewargs__(self, /)
  |
  | __gt__(self, value, /)
  |  Return self>value.
  |
  | __hash__(self, /)
  |  Return hash(self).
  |
  | __iter__(self, /)
  |  Implement iter(self).
  |
  | __le__(self, value, /)
  |  Return self<=value.
  |
  | __len__(self, /)
  |  Return len(self).
  |
  | __lt__(self, value, /)
  |  Return self<value.
  |
  | __mul__(self, value, /)
  |  Return self*value.
  |
  | __ne__(self, value, /)
  |  Return self!=value.
  |
  | __rmul__(self, value, /)
  |  Return value*self.
  |
  | count(self, value, /)
  |  Return number of occurrences of value.
  |
  | index(self, value, start=0, stop=9223372036854775807, /)
  |  Return first index of value.
  |
  |  Raises ValueError if the value is not present.

FUNCTIONS
 asctime(...)
  asctime([tuple]) -> string

  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.

 ctime(...)
  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.

 get_clock_info(...)
  get_clock_info(name: str) -> dict

  Get information of the specified clock.

 gmtime(...)
  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.

 localtime(...)
  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.

 mktime(...)
  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.

 monotonic(...)
  monotonic() -> float

  Monotonic clock, cannot go backward.

 monotonic_ns(...)
  monotonic_ns() -> int

  Monotonic clock, cannot go backward, as nanoseconds.

 perf_counter(...)
  perf_counter() -> float

  Performance counter for benchmarking.

 perf_counter_ns(...)
  perf_counter_ns() -> int

  Performance counter for benchmarking as nanoseconds.

 process_time(...)
  process_time() -> float

  Process time for profiling: sum of the kernel and user-space CPU time.

 process_time_ns(...)
  process_time() -> int

  Process time for profiling as nanoseconds:
  sum of the kernel and user-space CPU time.

 sleep(...)
  sleep(seconds)

  Delay execution for a given number of seconds. The argument may be
  a floating point number for subsecond precision.

 strftime(...)
  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].
  %d Day of the month as a decimal number [01,31].
  %H Hour (24-hour clock) as a decimal number [00,23].
  %M Minute as a decimal number [00,59].
  %S Second as a decimal number [00,61].
  %z Time zone offset from UTC.
  %a Locale's abbreviated weekday name.
  %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].
  %p Locale's equivalent of either AM or PM.

  Other codes may be available on your platform. See documentation for
  the C library strftime function.

 strptime(...)
  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()).

  Commonly used format codes:

  %Y Year with century as a decimal number.
  %m Month as a decimal number [01,12].
  %d Day of the month as a decimal number [01,31].
  %H Hour (24-hour clock) as a decimal number [00,23].
  %M Minute as a decimal number [00,59].
  %S Second as a decimal number [00,61].
  %z Time zone offset from UTC.
  %a Locale's abbreviated weekday name.
  %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].
  %p Locale's equivalent of either AM or PM.

  Other codes may be available on your platform. See documentation for
  the C library strftime function.

 thread_time(...)
  thread_time() -> float

  Thread time for profiling: sum of the kernel and user-space CPU time.

 thread_time_ns(...)
  thread_time() -> int

  Thread time for profiling as nanoseconds:
  sum of the kernel and user-space CPU time.

 time(...)
  time() -> floating point number

  Return the current time in seconds since the Epoch.
  Fractions of a second may be present if the system clock provides them.

 time_ns(...)
  time_ns() -> int

  Return the current time in nanoseconds since the Epoch.

DATA
 altzone = -32400
 daylight = 0
 timezone = -28800
 tzname = ('中国标准时间', '中国夏令时')

FILE
 (built-in)

None

Process finished with exit code 0

那么接下来我们挨个来看看

1. time.time()为当前时间戳,从1900年开始到当前时间的秒数

print(help(time.time)) # 打印帮助信息
print(time.time()) #1610720236.653394 # 打印当前时间戳
Help on built-in function time in module time:

time(...)
 time() -> floating point number

 Return the current time in seconds since the Epoch.
 Fractions of a second may be present if the system clock provides them.

None
1610727247.1696546

2. time.sleep(secs) 让程序暂停secs秒

1 print(help(time.sleep)) # 打印帮助信息
2 time.sleep(3) # 暂停3秒
Help on built-in function sleep in module time:

sleep(...)
 sleep(seconds)

 Delay execution for a given number of seconds. The argument may be
 a floating point number for subsecond precision.

None

3.time.gmtime() 结构化时间,不过要注意的一点是这个时间是世界标准时间(格林尼治时间)

1 print(help(time.gmtime)) # 打印帮助信息
2 print(time.gmtime()) # 结构化时间 time.struct_time(tm_year=2021, tm_mon=1, tm_mday=15, tm_hour=14, tm_min=22, tm_sec=30, tm_wday=4, tm_yday=15, tm_isdst=0)
Help on built-in function gmtime in module time:

gmtime(...)
 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.

None
time.struct_time(tm_year=2021, tm_mon=1, tm_mday=15, tm_hour=16, tm_min=16, tm_sec=39, tm_wday=4, tm_yday=15, tm_isdst=0)

不过这时肯定有人该问了,那我们的当地时间怎么表示呢,所以我们来介绍下一个

4.time.localtime()结构化时间,当前时间

1 print(help(time.localtime)) # 打印帮助信息
2 print(time.localtime()) # 当前结构化时间
Help on built-in function localtime in module time:

localtime(...)
 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.

None
time.struct_time(tm_year=2021, tm_mon=1, tm_mday=16, tm_hour=0, tm_min=17, tm_sec=49, tm_wday=5, tm_yday=16, tm_isdst=0)

总说结构化时间,那结构化时间是什么呢,我们来看看里面的参数

我们来拿上面这个例子来解释:

tm_year=2021     当前所在年
tm_mon=1         当前所在月
tm_mday=15       当前所在天
tm_hour=23       当前所在时
tm_min=18        当前所在分
tm_sec=57        当前所在秒
tm_wday=4        当前周的第几天
tm_yday=15       当前年的第几天

但是有时候我们需要的并不是结构化时间,而是类似于 2021-01-15 23:28:26 这样的格式化时间,那我们应该怎么做呢?

6. time.strftime() 将结构话时间化为格式化时间

1 print(help(time.strftime)) # 打印帮助信息
2 struct_time=time.localtime()
3 print(time.strftime("%Y-%m-%d %H:%M:%S",struct_time)) # 格式化时间
Help on built-in function strftime in module time:

strftime(...)
  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].
  %d Day of the month as a decimal number [01,31].
  %H Hour (24-hour clock) as a decimal number [00,23].
  %M Minute as a decimal number [00,59].
  %S Second as a decimal number [00,61].
  %z Time zone offset from UTC.
  %a Locale's abbreviated weekday name.
  %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].
  %p Locale's equivalent of either AM or PM.

  Other codes may be available on your platform. See documentation for
  the C library strftime function.

None
2021-01-16 00:18:38

同样这里为什么要写成 "%Y-%m-%d %H:%M:%S" 呢,就是为了控制时间的格式。

那这些都表示什么呢,我们来看看

%Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %a  Locale's abbreviated weekday name.
    %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].
    %p  Locale's equivalent of either AM or PM.

不过似乎也可以单独使用   time.strftime(),我们来看看结果,但是我们必须要把格式加上,如下所示:

print(time.strftime("%Y-%m-%d %H:%M:%S")) # 格式化时间
# 2021-01-15 23:36:49

那么,有时候我们也需要把格式化时间转化为结构化时间来使用,这时我们仅仅需要看看接下来的知识就能掌握

7. time.strptime() 将格式化时间(字符串)转化为结构化时间

print(help(time.strftime))
print(time.strftime("%Y-%m-%d %H:%M:%S")) # 格式化时间
# 2021-01-15 23:36:49
Help on built-in function strftime in module time:

strftime(...)
  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].
  %d Day of the month as a decimal number [01,31].
  %H Hour (24-hour clock) as a decimal number [00,23].
  %M Minute as a decimal number [00,59].
  %S Second as a decimal number [00,61].
  %z Time zone offset from UTC.
  %a Locale's abbreviated weekday name.
  %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].
  %p Locale's equivalent of either AM or PM.

  Other codes may be available on your platform. See documentation for
  the C library strftime function.

None
2021-01-16 00:20:46

当然以上只是一个举例,具体我们可以采用如下方式:

a=time.strptime("2021-01-15 22:26:28","%Y-%m-%d %H:%M:%S")
print(a.tm_yday)  # 15
print(a.tm_wday)  # 4

最后,我们快接近了尾声,最后我们再介绍两个就结束了

8. time.ctime() 将所给时间戳转变为一个格式化时间

1 print(help(time.ctime)) # 将时间戳转变为一个格式化时间
2 print(time.ctime())  # 如果不带参数则默认为当前时间戳
3 print(time.ctime(12412415))
Help on built-in function ctime in module time:

ctime(...)
  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.

None
Sat Jan 16 00:21:56 2021
Sun May 24 23:53:35 1970

9.time.mktime()  将所给结构化时间转化为时间戳

1 print(help(time.ctime)) # 打印帮助信息
2 print(time.mktime(time.localtime())) # 将结构化时间转化为时间戳
Help on built-in function ctime in module time:

ctime(...)
  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.

None
1610727764.0

不过值得一提的是,这种方式得到的时间戳精度要比time.time()低的多

最后,在提供一种其他求当前时间的方法

import datetime

print(datetime.datetime.now()) # 2021-01-15 23:55:48.985808

本次time模块便到此结束,其他模块下次讲解

总结

到此这篇关于Python学习之time模块的基本使用的文章就介绍到这了,更多相关Python time模块内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python基于time模块求程序运行时间的方法

    本文实例讲述了Python基于time模块求程序运行时间的方法.分享给大家供大家参考,具体如下: 要记录程序的运行时间可以利用Unix系统中,1970.1.1到现在的时间的毫秒数,这个时间戳轻松完成. 方法是程序开始的时候取一次存入一个变量,在程序结束之后取一次再存入一个变量,与程序开始的时间戳相减则可以求出. Python中取这个时间戳的方法为引入time类之后,使用time.time();就能够拿出来.也就是Java中的System.currentTimeMillis(). 由于Python

  • python time模块用法实例详解

    本文详细讲述了python的内嵌time模块的用法.分享给大家供大家参考之用.具体分析如下:   一.简介 time模块提供各种操作时间的函数 说明:一般有两种表示时间的方式: 第一种是时间戳的方式(相对于1970.1.1 00:00:00以秒计算的偏移量),时间戳是惟一的 第二种以数组的形式表示即(struct_time),共有九个元素,分别表示,同一个时间戳的struct_time会因为时区不同而不同 year (four digits, e.g. 1998) month (1-12) da

  • Python中的time模块与datetime模块用法总结

    time模块 time模块是包含各方面对时间操作的函数. 尽管这些常常有效但不是所有方法在任意平台中有效. time用struct_time表示时间 import time # time.struct_time(tm_year=2015, tm_mon=4, tm_mday=24, tm_hour=14, tm_min=17, tm_sec=26, tm_wday=4, tm_yday=114, tm_isdst=0) # 2015 print time.localtime() print ti

  • Python time模块详解(常用函数实例讲解,非常好)

    在开始之前,首先要说明这几点: 1.在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时间字符串 3)元组(struct_time)共九个元素.由于Python的time模块实现主要调用C库,所以各个平台可能有所不同.2.UTC(Coordinated Universal Time,世界协调时)亦即格林威治天文时间,世界标准时间.在中国为UTC+8.DST(Daylight Saving Time)即夏令时.3.时间戳(timestamp)的方式:通常来说,时间戳表示的是从1

  • Python之time模块的时间戳,时间字符串格式化与转换方法(13位时间戳)

    Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块. 关于时间戳的几个概念 时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量. 时间元组(struct_time),包含9个元素. time.struct_time(tm_year=2017, tm_mon=10, tm_mday=1, tm_hour=14, tm_min=21, tm_sec=57, tm_wday=6, tm_yday=274, tm_isdst=0) 时间格式字

  • Python中time模块与datetime模块在使用中的不同之处

    Python 中提供了对时间日期的多种多样的处理方式,主要是在 time 和 datetime 这两个模块里.今天稍微梳理一下这两个模块在使用上的一些区别和联系. time 在 Python 文档里,time是归类在Generic Operating System Services中,换句话说, 它提供的功能是更加接近于操作系统层面的.通读文档可知,time 模块是围绕着 Unix Timestamp 进行的. 该模块主要包括一个类 struct_time,另外其他几个函数及相关常量. 需要注意

  • 详解Python编程中time模块的使用

    一.简介 time模块提供各种操作时间的函数 说明:一般有两种表示时间的方式: 第一种是时间戳的方式(相对于1970.1.1 00:00:00以秒计算的偏移量),时间戳是惟一的 第二种以数组的形式表示即(struct_time),共有九个元素,分别表示,同一个时间戳的struct_time会因为时区不同而不同 year (four digits, e.g. 1998) month (1-12) day (1-31) hours (0-23) minutes (0-59) seconds (0-5

  • python模块之time模块(实例讲解)

    time 表示时间的三种形式 时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运行"type(time.time())",返回的是float类型. 格式化的时间字符串(Format String): '1999-12-06' 时间格式化符号 ''' %y 两位数的年份表示(00-99) %Y 四位数的年份表示(000-9999) %m 月份(01-12) %d 月内中的一天(0-31) %H 24小时制小时数(0-2

  • Python中time模块和datetime模块的用法示例

    time模块方法: time.time():获取当前时间的时间戳 time.localtime():接受一个时间戳,并把它转化为一个当前时间的元组.不给参数的话就会默认将time.time()作为参数传入 time.localtime(): 索引 属性 含义 0 tm_year 年 1 tm_mon 月 2 tm_mday 日 3 tm_hour 时 4 tm_min 分 5 tm_sec 秒 6 tm_wday 一周中的第几天 7 tm_yday 一年中的第几天 8 tm_isdst 夏令时

  • Python使用time模块实现指定时间触发器示例

    本文实例讲述了Python使用time模块实现指定时间触发器.分享给大家供大家参考,具体如下: 其实很简单,指定某个时间让脚本处理一个事件,比如说一个get请求~ 任何语言都会有关于时间的各种方法,Python也不例外. help(time)之后可以知道time有2种时间表示形式: 1.时间戳表示法,即以整型或浮点型表示的是一个以秒为单位的时间间隔.这个时间的基础值是从1970年的1月1号零点开始算起. 2.元组格式表示法,即一种python的数据结构表示.这个元组有9个整型内容.分别表示不同的

随机推荐