zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

Python日期 时间 相关 Time datetime calendar
2023-09-14 09:01:28 时间

函数 和 类:

>>> 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.

================================================================================
>>>