Answers:
实际上在Python中几乎是一样的.. :-)
import datetime
year = datetime.date.today().year
当然,日期没有时间,因此,如果您也很在意,您可以使用完整的datetime对象进行操作:
import datetime
year = datetime.datetime.today().year
(显然没有什么不同,但是当然可以在获取年份之前将datetime.datetime.today()存储在变量中)。
需要注意的一件事是在某些python版本(我认为是2.5.x树)中,时间分量在32位和64位python之间可能有所不同。因此,在某些64位平台上,您会发现诸如小时/分钟/秒之类的信息,而在32位平台上,您会发现时/分/秒。
import datetime
a = datetime.datetime.today().year
甚至(如Lennart建议的)
a = datetime.datetime.now().year
甚至
a = datetime.date.today().year
这个问题的其他答案似乎很快就到了。现在,您如何自己解决这个问题而又没有堆栈溢出?请查看IPython,它是一个具有选项卡自动完成功能的交互式Python shell。
> ipython
import Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
Type "copyright", "credits" or "license" for more information.
IPython 0.8.2.svn.r2750 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: import datetime
In [2]: now=datetime.datetime.now()
In [3]: now.
几次按Tab键,将提示您“ now”对象的成员:
now.__add__ now.__gt__ now.__radd__ now.__sub__ now.fromordinal now.microsecond now.second now.toordinal now.weekday
now.__class__ now.__hash__ now.__reduce__ now.astimezone now.fromtimestamp now.min now.strftime now.tzinfo now.year
now.__delattr__ now.__init__ now.__reduce_ex__ now.combine now.hour now.minute now.strptime now.tzname
now.__doc__ now.__le__ now.__repr__ now.ctime now.isocalendar now.month now.time now.utcfromtimestamp
now.__eq__ now.__lt__ now.__rsub__ now.date now.isoformat now.now now.timetuple now.utcnow
now.__ge__ now.__ne__ now.__setattr__ now.day now.isoweekday now.replace now.timetz now.utcoffset
now.__getattribute__ now.__new__ now.__str__ now.dst now.max now.resolution now.today now.utctimetuple
并且您会看到now.year是“ now”对象的成员。