Python datetime.toordinal()方法

Pythondatetime.toordinal() 方法是一种有效的方法,可以找到日期的顺位格雷戈里序数。注意,第1年的1月1日的序数为1,以此类推。

Pythondatetime.toordinal() 方法的语法

datetime.toordinal()

参数

这个方法不接受任何参数。

返回

该方法返回一个代表指定的datetime 对象的序数值的对象。

例1:在Python中使用datetime.toordinal() 方法

import datetime
datetime_object = datetime.date.today()
toordinal = datetime_object.toordinal()
print(f"The ordinal of the date {datetime_object} is {toordinal}.")

输出:

The ordinal of the date 2022-08-31 is 738398.

上面的代码显示了今天datetime 对象的格里高利序数。

例子 2: 输入超出范围的日期作为datetime.toordinal() 方法的一个参数

import datetime
date = datetime.datetime(18, 0, 0)
toordinal = date.toordinal()
print(f"The ordinal value of the earliest Datetime {date} is {toordinal}")

输出:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    date = datetime.datetime(18, 0, 0)
ValueError: month must be in 1..12

日期应该在给定的范围内,否则,会产生一个ValueError 异常。

例3:使用datetime.toordinal() 方法查找日号

import datetime
date = datetime.date(1776, 7, 4)
print("America got its independence on {}".format(date))
toordinal = date.toordinal()
print("America got its independence on {}th day if you count from 01/01/01".format(toordinal))

输出:

America got its independence on 1776-07-04
America got its independence on 648491th day if you count from 01/01/01

和上面的代码一样,你可以提到任何你想找到的具体日期的天数。

例4:用datetime.toordinal() 方法的最大值和最小值

import datetime
date = datetime.datetime(1, 1, 1, 0,0,0,0)
print("The ordinal number of the earliest possible date allowed",date," is: ", date.toordinal())
date = datetime.datetime(9999, 12, 31, 23, 59, 59)
print("The ordinal number of the largest maximum date allowed",date," is: ", date.toordinal())

输出结果:

The ordinal number of the earliest possible date allowed 0001-01-01 00:00:00  is:  1
The ordinal number of the largest maximum date allowed 9999-12-31 23:59:59  is:  3652059

公历只定义到9999年,不允许出现大于这个数字的年号。