我想從使用Python當前日期提取年份。如何從Python日期時間對象中提取年份?
在C#中,這看起來像:
DateTime a = DateTime.Now()
a.Year
什麼需要Python?
我想從使用Python當前日期提取年份。如何從Python日期時間對象中提取年份?
在C#中,這看起來像:
DateTime a = DateTime.Now()
a.Year
什麼需要Python?
這其實在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位的蟒蛇不同。因此,您可以在某些64位平臺上找到諸如小時/分鐘/秒之類的信息,而在32位系統上可以獲得小時/分鐘/秒。
import datetime
a = datetime.datetime.today().year
甚至(如梅里建議)
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.__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是其成員「現在」的對象。
如果你想從一個(未知)日期時間,對象的年份:
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
雖然現在()感覺上的日期時間更自然。 datetime.date.today()年,也許。 :) – 2009-07-15 18:43:53
我沒有想過這個問題,我想它確實感覺更「準確」的關於時間,在今日()似乎暗示天的精度。奇怪的是(至少在2.5.4)datetime.today()和datetime.now()做同樣的事情 – 2009-07-15 18:48:36