Python 与时间、日期相关的库 time, datetime, calendar

简介: Python 与时间、日期相关的库 time, datetime, calendar

函数 和 类:

>>> import time,datetime,calendar
>>> time
<module 'time' (built-in)>
>>> datetime
<module 'datetime' from 'D:\\Python\\lib\\datetime.py'>
>>> calendar
<module 'calendar' from 'D:\\Python\\lib\\calendar.py'>
>>> dir(time)
['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 
'altzone', 'asctime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 
'mktime', 'monotonic', 'monotonic_ns', 'perf_counter', 'perf_counter_ns', 'process_time', 
'process_time_ns', 'sleep', 'strftime', 'strptime', 'struct_time', 'thread_time', 
'thread_time_ns', 'time', 'time_ns', 'timezone', 'tzname']
>>>
>>> dir(datetime)
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', 
'__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 
'timedelta', 'timezone', 'tzinfo']
>>>
>>> dir(calendar)
['Calendar', 'EPOCH', 'FRIDAY', 'February', 'HTMLCalendar', 'IllegalMonthError', 
'IllegalWeekdayError', 'January', 'LocaleHTMLCalendar', 'LocaleTextCalendar', 'MONDAY', 
'SATURDAY', 'SUNDAY', 'THURSDAY', 'TUESDAY', 'TextCalendar', 'WEDNESDAY', '_EPOCH_ORD', 
'__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', 
'__package__', '__spec__', '_colwidth', '_locale', '_localized_day', '_localized_month', 
'_monthlen', '_nextmonth', '_prevmonth', '_spacing', 'c', 'calendar', 'datetime', 
'day_abbr', 'day_name', 'different_locale', 'error', 'firstweekday', 'format', 
'formatstring', 'isleap', 'leapdays', 'main', 'mdays', 'month', 'month_abbr', 'month_name', 
'monthcalendar', 'monthrange', 'prcal', 'prmonth', 'prweek', 'repeat', 'setfirstweekday', 
'sys', 'timegm', 'week', 'weekday', 'weekheader']
>>>



文档说明:

>>> print(time.__doc__)
time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object
All arguments are optional. tzinfo may be None, or an instance of
a tzinfo subclass. The remaining arguments may be ints.
>>> print(datetime.__doc__)
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
The year, month and day arguments are required. tzinfo may be None, or an
instance of a tzinfo subclass. The remaining arguments may be ints.
>>> print(calendar.__doc__)
        Returns a year's calendar as a multi-line string.



time库帮助:

>>> import time
>>> for i in [i for i in dir(time) if i[0]!='_']:
  print(i)
  help(eval('time.'+i))
  print('='*80)
altzone
[Squeezed text (254 lines).]
================================================================================
asctime
Help on built-in function asctime in module time:
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
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.
================================================================================
daylight
[Squeezed text (254 lines).]
================================================================================
get_clock_info
Help on built-in function get_clock_info in module time:
get_clock_info(...)
    get_clock_info(name: str) -> dict
    Get information of the specified clock.
================================================================================
gmtime
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.
================================================================================
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.
================================================================================
mktime
Help on built-in function mktime in module time:
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
Help on built-in function monotonic in module time:
monotonic(...)
    monotonic() -> float
    Monotonic clock, cannot go backward.
================================================================================
monotonic_ns
Help on built-in function monotonic_ns in module time:
monotonic_ns(...)
    monotonic_ns() -> int
    Monotonic clock, cannot go backward, as nanoseconds.
================================================================================
perf_counter
Help on built-in function perf_counter in module time:
perf_counter(...)
    perf_counter() -> float
    Performance counter for benchmarking.
================================================================================
perf_counter_ns
Help on built-in function perf_counter_ns in module time:
perf_counter_ns(...)
    perf_counter_ns() -> int
    Performance counter for benchmarking as nanoseconds.
================================================================================
process_time
Help on built-in function process_time in module time:
process_time(...)
    process_time() -> float
    Process time for profiling: sum of the kernel and user-space CPU time.
================================================================================
process_time_ns
Help on built-in function process_time_ns in module time:
process_time_ns(...)
    process_time() -> int
    Process time for profiling as nanoseconds:
    sum of the kernel and user-space CPU time.
================================================================================
sleep
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.
================================================================================
strftime
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.
================================================================================
strptime
Help on built-in function strptime in module time:
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.
================================================================================
struct_time
[Squeezed text (135 lines).]
================================================================================
thread_time
Help on built-in function thread_time in module time:
thread_time(...)
    thread_time() -> float
    Thread time for profiling: sum of the kernel and user-space CPU time.
================================================================================
thread_time_ns
Help on built-in function thread_time_ns in module time:
thread_time_ns(...)
    thread_time() -> int
    Thread time for profiling as nanoseconds:
    sum of the kernel and user-space CPU time.
================================================================================
time
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.
================================================================================
time_ns
Help on built-in function time_ns in module time:
time_ns(...)
    time_ns() -> int
    Return the current time in nanoseconds since the Epoch.
================================================================================
timezone
[Squeezed text (254 lines).]
================================================================================
tzname
[Squeezed text (81 lines).]
================================================================================


datetime库帮助:

>>> import datetime
>>> for i in [i for i in dir(datetime) if i[0]>'a']:
  print(i)
  help(eval('datetime.'+i))
  print('='*80)
date
[Squeezed text (133 lines).]
===============================================================================
datetime
[Squeezed text (215 lines).]
===============================================================================
datetime_CAPI
Help on PyCapsule object:
class PyCapsule(object)
 |  Capsule objects let you wrap a C "void *" pointer in a Python
 |  object.  They're a way of passing data through the Python interpreter
 |  without creating your own custom type.
 |  
 |  Capsules are used for communication between extension modules.
 |  They provide a way for an extension module to export a C interface
 |  to other extension modules, so that extension modules can use the
 |  Python import mechanism to link to one another.
 |  
 |  Methods defined here:
 |  
 |  __repr__(self, /)
 |      Return repr(self).
===============================================================================
sys
[Squeezed text (360 lines).]
===============================================================================
time
[Squeezed text (106 lines).]
===============================================================================
timedelta
[Squeezed text (129 lines).]
===============================================================================
timezone
[Squeezed text (78 lines).]
===============================================================================
tzinfo
Help on class tzinfo in module datetime:
class tzinfo(builtins.object)
 |  Abstract base class for time zone info objects.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __reduce__(...)
 |      -> (cls, state)
 |  
 |  dst(...)
 |      datetime -> DST offset as timedelta positive east of UTC.
 |  
 |  fromutc(...)
 |      datetime in UTC -> datetime in local time.
 |  
 |  tzname(...)
 |      datetime -> string name of time zone.
 |  
 |  utcoffset(...)
 |      datetime -> timedelta showing offset from UTC, negative values indicating West of UTC
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
===============================================================================
>>> 



calendar库帮助:

>>> import calendar
>>> for i in [i for i in dir(calendar) if (i[0])>='a']:
  print(i)
  help(eval('calendar.'+i))
  print('='*80)
c
[Squeezed text (121 lines).]
================================================================================
calendar
Help on method formatyear in module calendar:
formatyear(theyear, w=2, l=1, c=6, m=3) method of calendar.TextCalendar instance
    Returns a year's calendar as a multi-line string.
================================================================================
datetime
[Squeezed text (707 lines).]
================================================================================
day_abbr
Help on _localized_day in module calendar object:
class _localized_day(builtins.object)
 |  _localized_day(format)
 |  
 |  Methods defined here:
 |  
 |  __getitem__(self, i)
 |  
 |  __init__(self, format)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __len__(self)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
================================================================================
day_name
Help on _localized_day in module calendar object:
class _localized_day(builtins.object)
 |  _localized_day(format)
 |  
 |  Methods defined here:
 |  
 |  __getitem__(self, i)
 |  
 |  __init__(self, format)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __len__(self)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
================================================================================
different_locale
Help on class different_locale in module calendar:
class different_locale(builtins.object)
 |  different_locale(locale)
 |  
 |  Methods defined here:
 |  
 |  __enter__(self)
 |  
 |  __exit__(self, *args)
 |  
 |  __init__(self, locale)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
================================================================================
error
[Squeezed text (68 lines).]
================================================================================
firstweekday
Help on method getfirstweekday in module calendar:
getfirstweekday() method of calendar.TextCalendar instance
================================================================================
format
Help on function format in module calendar:
format(cols, colwidth=20, spacing=6)
    Prints multi-column formatting for year calendars
================================================================================
formatstring
Help on function formatstring in module calendar:
formatstring(cols, colwidth=20, spacing=6)
    Returns a string formatted from n strings, centered within n columns.
================================================================================
isleap
Help on function isleap in module calendar:
isleap(year)
    Return True for leap years, False for non-leap years.
================================================================================
leapdays
Help on function leapdays in module calendar:
leapdays(y1, y2)
    Return number of leap years in range [y1, y2).
    Assume y1 <= y2.
================================================================================
main
Help on function main in module calendar:
main(args)
================================================================================
mdays
[Squeezed text (135 lines).]
================================================================================
month
Help on method formatmonth in module calendar:
formatmonth(theyear, themonth, w=0, l=0) method of calendar.TextCalendar instance
    Return a month's calendar string (multi-line).
================================================================================
month_abbr
Help on _localized_month in module calendar object:
class _localized_month(builtins.object)
 |  _localized_month(format)
 |  
 |  Methods defined here:
 |  
 |  __getitem__(self, i)
 |  
 |  __init__(self, format)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __len__(self)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
================================================================================
month_name
Help on _localized_month in module calendar object:
class _localized_month(builtins.object)
 |  _localized_month(format)
 |  
 |  Methods defined here:
 |  
 |  __getitem__(self, i)
 |  
 |  __init__(self, format)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __len__(self)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
================================================================================
monthcalendar
Help on method monthdayscalendar in module calendar:
monthdayscalendar(year, month) method of calendar.TextCalendar instance
    Return a matrix representing a month's calendar.
    Each row represents a week; days outside this month are zero.
================================================================================
monthrange
Help on function monthrange in module calendar:
monthrange(year, month)
    Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
    year, month.
================================================================================
prcal
Help on method pryear in module calendar:
pryear(theyear, w=0, l=0, c=6, m=3) method of calendar.TextCalendar instance
    Print a year's calendar.
================================================================================
prmonth
Help on method prmonth in module calendar:
prmonth(theyear, themonth, w=0, l=0) method of calendar.TextCalendar instance
    Print a month's calendar.
================================================================================
prweek
Help on method prweek in module calendar:
prweek(theweek, width) method of calendar.TextCalendar instance
    Print a single week (no newline).
================================================================================
repeat
Help on class repeat in module itertools:
class repeat(builtins.object)
 |  repeat(object [,times]) -> create an iterator which returns the object
 |  for the specified number of times.  If not specified, returns the object
 |  endlessly.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __length_hint__(...)
 |      Private method returning an estimate of len(list(it)).
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  __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.
================================================================================
setfirstweekday
Help on function setfirstweekday in module calendar:
setfirstweekday(firstweekday)
================================================================================
sys
[Squeezed text (358 lines).]
================================================================================
timegm
Help on function timegm in module calendar:
timegm(tuple)
    Unrelated but handy function to calculate Unix timestamp from GMT.
================================================================================
week
Help on method formatweek in module calendar:
formatweek(theweek, width) method of calendar.TextCalendar instance
    Returns a single week in a string (no newline).
================================================================================
weekday
Help on function weekday in module calendar:
weekday(year, month, day)
    Return weekday (0-6 ~ Mon-Sun) for year, month (1-12), day (1-31).
================================================================================
weekheader
Help on method formatweekheader in module calendar:
formatweekheader(width) method of calendar.TextCalendar instance
    Return a header for a week.
================================================================================
>>>
目录
相关文章
|
3天前
|
XML 前端开发 数据格式
BeautifulSoup 是一个 Python 库,用于从 HTML 和 XML 文件中提取数据
BeautifulSoup 是 Python 的一个库,用于解析 HTML 和 XML 文件,即使在格式不规范的情况下也能有效工作。通过创建 BeautifulSoup 对象并使用方法如 find_all 和 get,可以方便地提取和查找文档中的信息。以下是一段示例代码,展示如何安装库、解析 HTML 数据以及打印段落、链接和特定类名的元素。BeautifulSoup 还支持更复杂的查询和文档修改功能。
11 1
|
22小时前
|
机器学习/深度学习 数据挖掘 PyTorch
10个非常有用的Python库,你知道几个?
这些库覆盖了数据科学、机器学习、Web开发和其他领域,使Python成为一个多用途的编程语言。它们在各种项目和领域中都非常有用。
15 2
|
1天前
|
SQL 关系型数据库 数据库连接
使用 Python 访问数据库的基本方法
【5月更文挑战第12天】在Python中操作数据库涉及安装数据库驱动(如mysql-connector-python, psycopg2, pymongo)、连接数据库、执行查询/更新、处理结果集及关闭连接。使用ORM(如SQLAlchemy)可简化操作。通过上下文管理器(with语句)能更好地管理资源和错误。注意根据实际需求处理事务、错误和安全性,例如使用SSL连接。
11 2
|
2天前
|
JSON 监控 调度
局域网管理软件的自动化任务调度:Python 中的 APScheduler 库的应用
使用 Python 的 APScheduler 库可简化局域网管理中的自动化任务调度。APScheduler 是一个轻量级定时任务调度库,支持多种触发方式如间隔、时间、日期和 Cron 表达式。示例代码展示了如何创建每 10 秒执行一次的定时任务。在局域网管理场景中,可以利用 APScheduler 定期监控设备状态,当设备离线时自动提交数据到网站,提升管理效率。
14 0
|
2天前
|
数据采集 数据可视化 数据挖掘
如何利用Python中的Pandas库进行数据分析和可视化
Python的Pandas库是一种功能强大的工具,可以用于数据分析和处理。本文将介绍如何使用Pandas库进行数据分析和可视化,包括数据导入、清洗、转换以及基本的统计分析和图表绘制。通过学习本文,读者将能够掌握利用Python中的Pandas库进行高效数据处理和可视化的技能。
|
4天前
|
机器学习/深度学习 自然语言处理 算法
Gensim详细介绍和使用:一个Python文本建模库
Gensim详细介绍和使用:一个Python文本建模库
15 1
|
4天前
|
JSON 数据格式 Python
Python 的 requests 库是一个强大的 HTTP 客户端库,用于发送各种类型的 HTTP 请求
`requests` 库是 Python 中用于HTTP请求的强大工具。要开始使用,需通过 `pip install requests` 进行安装。发送GET请求可使用 `requests.get(url)`,而POST请求则需结合 `json.dumps(data)` 以JSON格式发送数据。PUT和DELETE请求类似,分别调用 `requests.put()` 和 `requests.delete()`。
14 2
|
4月前
|
Python
Python通过导入 calendar 模块来计算每个月的天
Python通过导入 calendar 模块来计算每个月的天
|
前端开发 Python
第36天:Python calendar 模块
第36天:Python calendar 模块
94 0