繁体   English   中英

Python 中的 now = datetime.datetime.now() 和 now = datetime.now() 有什么区别?

[英]What is the difference between now = datetime.datetime.now() and now = datetime.now() in Python?

Python 中的now = datetime.datetime.now()now = datetime.now()有什么区别? 为什么需要重复datetime时间?

>>> import datetime

>>> datetime.datetime.now()
datetime.datetime(2021, 3, 5, 11, 30, 26, 254912)

>>> datetime.now()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: module 'datetime' has no attribute 'now'

>>> type(datetime)
<class 'module'>

>>>type(datetime.datetime)
<class 'type'>

datetime 是一个 python 模块,其中存在“DateTime 类”。 当我们调用 datetime.datetime 时,一个新的 object 由 class 创建。 “DateTime 类”具有不同的功能,提供日期、年份、月份等。

如果您只是在执行import datetime ,我认为now = datetime.now()不会起作用

对于您关于为什么重复日期时间的问题。

当我们说import datetime时,我们正在导入一个名为 datetime 的模块。 在该模块中,有用于进一步操作的不同基类。 它们是date, time, datetime等。

基本上第二个日期时间是 class 的名称,用于处理日期和时间操作。 如果您只想执行与日期相关的操作,您可以使用datetime.date class。 如需进一步说明,请查看官方文档

https://docs.python.org/3/library/datetime.html

简而言之,如果您想使用datetime时间 package 的多个功能,您可能会

import datetime

并且需要引用datetime.datetime.now()的全名。 如果您只需要datetime.datetime中的功能,则可以通过以下方式缩写它

from datetime import datetime

然后datetime.now()解析为datetime.datetime.now()因为符号datetime实际上是指源文件中的datetime.datetime

具有两个相同标签的嵌套结构既指库又指特定子模块,这不是理想的设计。 Many Python packages (both in the standard library, and more broadly) have unattractive import conventions where the only thing you could possibly want to import needs to be imported with the from package import submodule syntax, or you are stuck with having to use package.submodule每当您想引用package.submodule中的某些内容时, submodule

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM