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模塊內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: