Python 日期时间库datetime常用函数

简介: Python 日期时间库datetime常用函数

moduledatetime


1. class date(builtins.object)


date(year, month, day) --> date object

参数:年月日为三个整数,最大值9999,12,31,最小值1,1,1;返回值为日期对象。

>>> import datetime as d
>>> [i for i in dir(d) if i[0]>='a']
['date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']
>>> help(d.date)
Help on class date in module datetime:
class date(builtins.object)
 |  date(year, month, day) --> date object
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(...)
 |      Formats self with strftime.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __radd__(self, value, /)
 |      Return value+self.
 |  
 |  __reduce__(...)
 |      __reduce__() -> (cls, state)
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rsub__(self, value, /)
 |      Return value-self.
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  __sub__(self, value, /)
 |      Return self-value.
 |  
 |  ctime(...)
 |      Return ctime() style string.
 |  
 |  isocalendar(...)
 |      Return a 3-tuple containing ISO year, week number, and weekday.
 |  
 |  isoformat(...)
 |      Return string in ISO 8601 format, YYYY-MM-DD.
 |  
 |  isoweekday(...)
 |      Return the day of the week represented by the date.
 |      Monday == 1 ... Sunday == 7
 |  
 |  replace(...)
 |      Return date with new specified fields.
 |  
 |  strftime(...)
 |      format -> strftime() style string.
 |  
 |  timetuple(...)
 |      Return time tuple, compatible with time.localtime().
 |  
 |  toordinal(...)
 |      Return proleptic Gregorian ordinal.  January 1 of year 1 is day 1.
 |  
 |  weekday(...)
 |      Return the day of the week represented by the date.
 |      Monday == 0 ... Sunday == 6
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  fromisocalendar(...) from builtins.type
 |      int, int, int -> Construct a date from the ISO year, week number and weekday.
 |      
 |      This is the inverse of the date.isocalendar() function
 |  
 |  fromisoformat(...) from builtins.type
 |      str -> Construct a date from the output of date.isoformat()
 |  
 |  fromordinal(...) from builtins.type
 |      int -> date corresponding to a proleptic Gregorian ordinal.
 |  
 |  fromtimestamp(timestamp, /) from builtins.type
 |      Create a date from a POSIX timestamp.
 |      
 |      The timestamp is a number, e.g. created via time.time(), that is interpreted
 |      as local time.
 |  
 |  today(...) from builtins.type
 |      Current date or datetime:  same as self.__class__.fromtimestamp(time.time()).
 |  
 |  ----------------------------------------------------------------------
 |  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:
 |  
 |  day
 |  
 |  month
 |  
 |  year
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  max = datetime.date(9999, 12, 31)
 |  
 |  min = datetime.date(1, 1, 1)
 |  
 |  resolution = datetime.timedelta(days=1)
>>> 



例:

>>> import datetime
>>> datetime.date(2021,5,16)
datetime.date(2021, 5, 16)
>>> Yesterday=datetime.date(2021,5,16)
>>> Today=datetime.date.today()
>>> Today.__eq__(Yesterday)
False
>>> Yesterday.__le__(Today)
True
>>> Yesterday.ctime()
'Sun May 16 00:00:00 2021'
>>> Yesterday.isocalendar()
(2021, 19, 7)
>>> Today.isocalendar()
(2021, 20, 1)
>>> datetime.date(2019,1,1).isocalendar()
(2019, 1, 2)
>>> datetime.date(2021,1,1).isocalendar()
(2020, 53, 5)
>>> datetime.date(2021,1,3).isocalendar()
(2020, 53, 7)
>>> datetime.date(2021,1,4).isocalendar()
(2021, 1, 1)
>>> #方法.isocalendar返回值是一年中的第几周第几天
>>> Yesterday.isoformat()
'2021-05-16'
>>> Today.replace(2020)
datetime.date(2020, 5, 17)
>>> Today.replace(2021,1)
datetime.date(2021, 1, 17)
>>> Today.replace(2021,5,16)
datetime.date(2021, 5, 16)
>>> Yesterday.isoweekday()
7
>>> Today.isoweekday()
1
>>> Yesterday.weekday()
6
>>> Today.weekday()
0
>>> Today.timetuple()
time.struct_time(tm_year=2021, tm_mon=5, tm_mday=17, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=137, tm_isdst=-1)
>>> Today.toordinal()
737927
>>> Yesterday.toordinal()
737926
>>> #方法.toordinal()返回值以‘1-1-1’为第1天
>>> 


2. class date(builtins.object)

time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object

参数:时[分秒...],最少一个参数;返回值为时间对象。

>>> help(datetime.time)
Help on class time in module datetime:
class time(builtins.object)
 |  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.
 |  
 |  Methods defined here:
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(...)
 |      Formats self with strftime.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __reduce__(...)
 |      __reduce__() -> (cls, state)
 |  
 |  __reduce_ex__(...)
 |      __reduce_ex__(proto) -> (cls, state)
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  dst(...)
 |      Return self.tzinfo.dst(self).
 |  
 |  isoformat(...)
 |      Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].
 |      
 |      The optional argument timespec specifies the number of additional terms
 |      of the time to include. Valid options are 'auto', 'hours', 'minutes',
 |      'seconds', 'milliseconds' and 'microseconds'.
 |  
 |  replace(...)
 |      Return time with new specified fields.
 |  
 |  strftime(...)
 |      format -> strftime() style string.
 |  
 |  tzname(...)
 |      Return self.tzinfo.tzname(self).
 |  
 |  utcoffset(...)
 |      Return self.tzinfo.utcoffset(self).
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  fromisoformat(...) from builtins.type
 |      string -> time from time.isoformat() output
 |  
 |  ----------------------------------------------------------------------
 |  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:
 |  
 |  fold
 |  
 |  hour
 |  
 |  microsecond
 |  
 |  minute
 |  
 |  second
 |  
 |  tzinfo
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  max = datetime.time(23, 59, 59, 999999)
 |  
 |  min = datetime.time(0, 0)
 |  
 |  resolution = datetime.timedelta(microseconds=1)


目录
相关文章
|
2天前
|
机器学习/深度学习 存储 数据挖掘
Python图像处理实用指南:PIL库的多样化应用
本文介绍Python中PIL库在图像处理中的多样化应用,涵盖裁剪、调整大小、旋转、模糊、锐化、亮度和对比度调整、翻转、压缩及添加滤镜等操作。通过具体代码示例,展示如何轻松实现这些功能,帮助读者掌握高效图像处理技术,适用于图片美化、数据分析及机器学习等领域。
39 20
|
1月前
|
XML JSON 数据库
Python的标准库
Python的标准库
169 77
|
7天前
|
Python
[oeasy]python057_如何删除print函数_dunder_builtins_系统内建模块
本文介绍了如何删除Python中的`print`函数,并探讨了系统内建模块`__builtins__`的作用。主要内容包括: 1. **回忆上次内容**:上次提到使用下划线避免命名冲突。 2. **双下划线变量**:解释了双下划线(如`__name__`、`__doc__`、`__builtins__`)是系统定义的标识符,具有特殊含义。
20 3
|
11天前
|
JSON 监控 安全
深入理解 Python 的 eval() 函数与空全局字典 {}
`eval()` 函数在 Python 中能将字符串解析为代码并执行,但伴随安全风险,尤其在处理不受信任的输入时。传递空全局字典 {} 可限制其访问内置对象,但仍存隐患。建议通过限制函数和变量、使用沙箱环境、避免复杂表达式、验证输入等提高安全性。更推荐使用 `ast.literal_eval()`、自定义解析器或 JSON 解析等替代方案,以确保代码安全性和可靠性。
24 2
|
1月前
|
Python
Python中的函数是**一种命名的代码块,用于执行特定任务或计算
Python中的函数是**一种命名的代码块,用于执行特定任务或计算
52 18
|
30天前
|
数据可视化 DataX Python
Seaborn 教程-绘图函数
Seaborn 教程-绘图函数
62 8
|
1月前
|
XML JSON 数据库
Python的标准库
Python的标准库
51 11
|
1月前
|
数据可视化 Python
以下是一些常用的图表类型及其Python代码示例,使用Matplotlib和Seaborn库。
通过这些思维导图和分析说明表,您可以更直观地理解和选择适合的数据可视化图表类型,帮助更有效地展示和分析数据。
73 8
|
8月前
|
安全 Python
Python如何使用datetime模块进行日期和时间的操作
Python如何使用datetime模块进行日期和时间的操作
79 1
|
Python
python时间和日期操作(datetime和monthrange,timedelta)
python时间和日期操作(datetime和monthrange,timedelta)
174 0