如何从Pythondate时间对象中提取年份?

我想使用Python从当前date中提取年份。

在C#中,这看起来像:

DateTime a = DateTime.Now() a.Year 

Python中需要什么?

它实际上在Python中几乎是一样的。:-)

 import datetime year = datetime.date.today().year 

当然,date没有时间关联,所以如果你也关心,你可以用一个完整的date时间对象来做同样的事情:

 import datetime year = datetime.datetime.today().year 

(显然没有什么不同,但是你可以将datetime.datetime.today()存储在一个variables中,然后才能抓取年份)。

需要注意的一点是,在一些python版本(我认为是2.5.x版本)中,时间组件可以在32位和64位python之间有所不同。 所以你可以在一些64位平台上find像小时/分钟/秒这样的东西,而在32位上可以得到小时/分钟/秒。

 import datetime a = datetime.datetime.today().year 

甚至(如Lennart所build议的)

 a = datetime.datetime.now().year 

甚至

 a = datetime.date.today().year 

这个问题的其他答案似乎打上了现场。 现在你怎样才能知道自己没有堆栈溢出? 查看IPython ,这是一个具有标签自动完成function的交互式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. 

按下标签几次,你会被提示“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”对象的成员。

如果你想从一个(未知)date时间对象的年份:

 tijd = datetime.datetime(9999, 12, 31, 23, 59, 59) >>> tijd.timetuple() time.struct_time(tm_year=9999, tm_mon=12, tm_mday=31, tm_hour=23, tm_min=59, tm_sec=59, tm_wday=4, tm_yday=365, tm_isdst=-1) >>> tijd.timetuple().tm_year 9999