我想使用Python从当前日期中提取年份。
在C#中,这看起来像:
DateTime a = DateTime.Now()
a.Year
Python需要什么?
答案 0 :(得分:90)
事实上,它在Python中几乎相同..: - )
import datetime
year = datetime.date.today().year
当然,日期没有时间关联,所以如果你也关心它,你也可以使用完整的日期时间对象:
import datetime
year = datetime.datetime.today().year
(显然没有什么不同,但你可以在获取年份之前将datetime.datetime.today()存储在变量中。)
需要注意的一件事是,在某些python版本中,时间组件在32位和64位pyth之间可能不同(我认为是2.5.x树)。因此,您会在某些64位平台上找到小时/分钟/秒等内容,而在32位平台上可以获得小时/分钟/秒。
答案 1 :(得分:17)
import datetime
a = datetime.datetime.today().year
或甚至(作为Lennart suggested)
a = datetime.datetime.now().year
甚至
a = datetime.date.today().year
答案 2 :(得分:12)
这个问题的其他答案似乎点击了它。现在如何在没有堆栈溢出的情况下为自己解决这个问题?查看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”对象的成员。
答案 3 :(得分:3)
如果您想要来自(未知)datetime-object的年份:
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