Python datetime.toordinal() 方法
datetime.toordinal() 方法用於操作模塊 datetime 的 datetime 類的對象。
它用於返回日期的預測格列高利序數,其中第 1 年的 1 月 1 日的序數為 1。如果第 1 年的 1 月 1 日的序數為 1,則第 1 年的 1 月 2 日的序數為 2,依此類推。它是一個實例方法,這意味著它適用於類的實例。
模塊:
import datetime
類:
from datetime import datetime
用法:
toordinal()
參數:
- None
返回值:
此方法的返回類型是一個數字,它是該日期在公曆中的序數。
例:
## importing datetime class
from datetime import datetime
## Creating an instance
x = datetime(2020,10,27, 21, 5,27, 100)
d = x.toordinal()
print("Ordinal number of date ",x," is:", d)
print()
## Using today' date
x = datetime.now()
d = x.toordinal()
print("Ordinal number of date ",x," is:", d)
print()
x = datetime.today()
d = x.toordinal()
print("Ordinal number of date ",x," is:", d)
print()
x = datetime(1, 1, 1, 0,0,0,0)
d = x.toordinal()
print("Ordinal number of the earliest possible date allowed",x," is:", d)
print()
x = datetime(9999, 12, 31, 23, 59, 59)
d = x.toordinal()
print("Ordinal number of the largest maximum date allowed",x," is:", d)
print()
輸出
Ordinal number of date 2020-10-27 21:05:27.000100 is:737725 Ordinal number of date 2020-05-02 06:50:06.336005 is:737547 Ordinal number of date 2020-05-02 06:50:06.336068 is:737547 Ordinal number of the earliest possible date allowed 0001-01-01 00:00:00 is:1 Ordinal number of the largest maximum date allowed 9999-12-31 23:59:59 is:3652059
注意:日期時間對象的屬性應在給定範圍內,否則將顯示 ValueError。
例:
## importing datetime class
from datetime import datetime
## Creating an instance
x = datetime(99999, 1, 31)
d = x.toordinal()
print("Ordinal number of the date",x," is:", d)
print()
輸出
Traceback (most recent call last): File "main.py", line 5, in <module> x = datetime(99999, 1, 31) ValueError:year 99999 is out of range
相關用法
- Python datetime timetuple()用法及代碼示例
- Python datetime timetz()用法及代碼示例
- Python datetime time()用法及代碼示例
- Python datetime tzname()用法及代碼示例
- Python datetime astimezone()用法及代碼示例
- Python datetime isocalendar()用法及代碼示例
- Python datetime date()用法及代碼示例
- Python datetime isoformat()用法及代碼示例
- Python datetime __str__()用法及代碼示例
- Python datetime utcoffset()用法及代碼示例
- Python datetime weekday()用法及代碼示例
- Python datetime replace()用法及代碼示例
- Python datetime strftime()用法及代碼示例
- Python datetime isoweekday()用法及代碼示例
- Python datetime.timedelta()用法及代碼示例
- Python datetime.tzinfo()用法及代碼示例
- Python date toordinal()用法及代碼示例
- Python date replace()用法及代碼示例
- Python date strftime()用法及代碼示例
- Python date weekday()用法及代碼示例
注:本文由純淨天空篩選整理自 Python datetime toordinal() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。