如何从Python的日期时间对象中提取年份?

168
我想使用Python从当前日期中提取年份。在C#中,这看起来像:
 DateTime a = DateTime.Now() 
 a.Year

Python需要什么?

5个回答

244

实际上在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位平台上你会得到小时/分/秒。


3
datetime.datetime.today().year 在Python 3中无法使用。它会返回一个错误 _AttributeError: type object 'datetime.datetime' has no attribute 'datetime'_。我不得不使用 datetime.today().year - twumm
8
@twumm, 这是因为你将 datetime 导入为 "from datetime import datetime"。如果你只是简单地使用 "import datetime",解决方案就可以正常工作。这与你现在的代码完全相同。 - Apteronotus

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

或者甚至(如Lennart建议的那样

a = datetime.datetime.now().year
甚至更多
a = datetime.date.today().year

3
尽管在datetime中使用now()更自然,但也可以使用datetime.date.today().year。 :) - Lennart Regebro
我之前没有考虑到这一点,我猜它在时间上更加“准确”,而today()可能会给人一种天数精度的感觉。奇怪的是(datetime.today()和datetime.now())在2.5.4版本中做了相同的事情。 - user44484
它们并不完全相同,datetime.now()接受一个时区对象,而datetime.today()只是从fromtimestamp(time.time())调用,因此today()始终会在Python认为的本地时区中,而你可以让now()告诉你稍微有趣一些的东西。 - Nick Bastin

21

看起来其他回答已经解决了这个问题。那么如果没有Stack Overflow,你该如何自己解决呢?可以参考IPython。这是一个交互式的Python shell,可以使用Tab键自动完成。

> 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" 对象的一个成员。


2
此外,这是:http://docs.python.org/library/datatypes.html。 不过谢谢,我不知道关于IPython的那个。 - user44484
3
解决问题的赞扬 - 补充实际解决方案。 - Iceland_jack
对于那些不想安装IPython的人,你可以使用dir来包装任何函数或类以查看可能的方法和属性。例如,dir(datetime.datetime.now)将为您提供可用的函数,就像在IPython中按tab键一样。 - Saurav Pathak

9

如果您想从一个(未知的)日期时间对象中获取年份:

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

4

提取年份很简单,可以按照以下方式进行。

from datetime import datetime

year = datetime.today().year

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接