如何导入datetime.now,以便我可以使用now()进行调用?
问题描述:
我希望能够在程序中调用datetime.now()
.
I want to be able to call datetime.now()
in my program.
-
import datetime
要求我做datetime.datetime.now()
-
from datetime import datetime
仍然需要我做datetime.now()
-
from datetime.datetime import now
无法编译
-
import datetime
requires me to dodatetime.datetime.now()
-
from datetime import datetime
still requires me to dodatetime.now()
-
from datetime.datetime import now
doesn't compile
有没有一种方法可以导入它,而不必指定父类? IE.我希望能够执行t = now()
而不是t = datetime.now()
.
Is there a way to import it so that I don't have to specify the parent classes? Ie. I want to be able to do t = now()
as opposed to t = datetime.now()
.
答
您不能直接导入datetime.datetime.now
,因为datetime
不是不是模块,它实际上是一个类,并且now
是一种分类方法. 这里是有关导入静态方法的类似问题.
You can't import datetime.datetime.now
directly because datetime
is not a module, it is actually a class, and now
is a classmethod. Here is a similar question regarding import static methods.
这是一个最小的工作代码,可以执行您需要的操作.
Here is a minimal working code to be able to do what you need.
import datetime
now = datetime.datetime.now