简体   繁体   English

导入和使用datetime python库的正确方法

[英]The correct way to import and use the datetime python library

Why can't I just do datetime.now()? 为什么我不能只做datetime.now()? Python doesn't like this?? Python不喜欢这样吗? Whats the correct why to import and use the datetime library in python...? 为什么要在python中导入和使用datetime库,正确的是什么?

import datetime
now = datetime.datetime.now()
print "Time: %d:%02d - Date: %d/%d/%d <br>" %(now.hour, now.minute, now.month, now.day, now.year)

That's because you are importing the datetime module (which contains classes for manipulating dates and times as stated in the documentation ) not the datetime object. 那是因为您要导入的是datetime模块(其中包含用于处理文档中所述的日期和时间的类),而不是datetime对象。 In such classes and objects inside the datetime module exists an object named datetime (yes, the same name as the module where it lives), so to use the datetime object the way you want you need to import it like this: 在datetime模块内部的此类类和对象中,存在一个名为datetime的对象(是的,与它所在的模块的名称相同),因此要以所需的方式使用datetime对象,您需要这样导入:

from datetime import datetime
#       ^               ^
#       |               |
#    module      class inside module

# Now you can use
now = datetime.now()

The datetime module contains a number of classes , including the class datetime.datetime . datetime 模块包含许多 ,包括类datetime.datetime If you don't care about the other functions in the module, you can write: 如果您不关心模块中的其他功能,则可以编写:

from datetime import datetime as datetime_class
datetime_class.now()

However, I strongly suggest simply writing datetime.datetime.now() . 但是,我强烈建议您简单地编写datetime.datetime.now()

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

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