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.
================================================================================
>>>
目录
相关文章
|
18天前
|
Python
python的时间操作time
【10月更文挑战第18天】 python的时间操作time
36 5
|
6天前
|
调度 开发者 Python
Python中的异步编程:理解asyncio库
在Python的世界里,异步编程是一种高效处理I/O密集型任务的方法。本文将深入探讨Python的asyncio库,它是实现异步编程的核心。我们将从asyncio的基本概念出发,逐步解析事件循环、协程、任务和期货的概念,并通过实例展示如何使用asyncio来编写异步代码。不同于传统的同步编程,异步编程能够让程序在等待I/O操作完成时释放资源去处理其他任务,从而提高程序的整体效率和响应速度。
|
9天前
|
数据采集 存储 数据挖掘
Python数据分析:Pandas库的高效数据处理技巧
【10月更文挑战第27天】在数据分析领域,Python的Pandas库因其强大的数据处理能力而备受青睐。本文介绍了Pandas在数据导入、清洗、转换、聚合、时间序列分析和数据合并等方面的高效技巧,帮助数据分析师快速处理复杂数据集,提高工作效率。
33 0
|
2天前
|
数据库 Python
异步编程不再难!Python asyncio库实战,让你的代码流畅如丝!
在编程中,随着应用复杂度的提升,对并发和异步处理的需求日益增长。Python的asyncio库通过async和await关键字,简化了异步编程,使其变得流畅高效。本文将通过实战示例,介绍异步编程的基本概念、如何使用asyncio编写异步代码以及处理多个异步任务的方法,帮助你掌握异步编程技巧,提高代码性能。
12 4
|
2天前
|
API 数据处理 Python
探秘Python并发新世界:asyncio库,让你的代码并发更优雅!
在Python编程中,随着网络应用和数据处理需求的增长,并发编程变得愈发重要。asyncio库作为Python 3.4及以上版本的标准库,以其简洁的API和强大的异步编程能力,成为提升性能和优化资源利用的关键工具。本文介绍了asyncio的基本概念、异步函数的定义与使用、并发控制和资源管理等核心功能,通过具体示例展示了如何高效地编写并发代码。
11 2
|
8天前
|
数据采集 JSON 测试技术
Python爬虫神器requests库的使用
在现代编程中,网络请求是必不可少的部分。本文详细介绍 Python 的 requests 库,一个功能强大且易用的 HTTP 请求库。内容涵盖安装、基本功能(如发送 GET 和 POST 请求、设置请求头、处理响应)、高级功能(如会话管理和文件上传)以及实际应用场景。通过本文,你将全面掌握 requests 库的使用方法。🚀🌟
29 7
|
8天前
|
机器学习/深度学习 数据采集 算法
Python机器学习:Scikit-learn库的高效使用技巧
【10月更文挑战第28天】Scikit-learn 是 Python 中最受欢迎的机器学习库之一,以其简洁的 API、丰富的算法和良好的文档支持而受到开发者喜爱。本文介绍了 Scikit-learn 的高效使用技巧,包括数据预处理(如使用 Pipeline 和 ColumnTransformer)、模型选择与评估(如交叉验证和 GridSearchCV)以及模型持久化(如使用 joblib)。通过这些技巧,你可以在机器学习项目中事半功倍。
19 3
|
11天前
|
数据采集 数据可视化 数据处理
如何使用Python实现一个交易策略。主要步骤包括:导入所需库(如`pandas`、`numpy`、`matplotlib`)
本文介绍了如何使用Python实现一个交易策略。主要步骤包括:导入所需库(如`pandas`、`numpy`、`matplotlib`),加载历史数据,计算均线和其他技术指标,实现交易逻辑,记录和可视化交易结果。示例代码展示了如何根据均线交叉和价格条件进行开仓、止损和止盈操作。实际应用时需注意数据质量、交易成本和风险管理。
31 5
|
10天前
|
存储 数据挖掘 数据处理
Python数据分析:Pandas库的高效数据处理技巧
【10月更文挑战第26天】Python 是数据分析领域的热门语言,Pandas 库以其高效的数据处理功能成为数据科学家的利器。本文介绍 Pandas 在数据读取、筛选、分组、转换和合并等方面的高效技巧,并通过示例代码展示其实际应用。
24 1
|
16天前
|
Python
python的时间操作time-应用
【10月更文挑战第20天】 python模块time的函数使用。
40 7
下一篇
无影云桌面