📜  Python – datetime.toordinal() 方法和示例

📅  最后修改于: 2022-05-13 01:54:34             🧑  作者: Mango

Python – datetime.toordinal() 方法和示例

datetime.toordinal()是一种用于操作 DateTime 类对象的简单方法。它返回日期的预测公历序号,其中第 1 年的 1 月 1 日的序号为 1。该函数返回给定 DateTime 对象的序号值。

如果第 1 年的 1 月 1 日的序号为 1,则第 1 年的 1 月 2 日的序号为 2,依此类推。

下面给出了相同的一些实现。

示例 1:使用datetime.toordinal()函数使用 datetime 模块的 date.today() 类返回给定日期时间对象的公历序数。

Python3
# Python3 code to demonstrate
# Getting Ordinal value using
# toordinal().
 
# importing datetime module for today()
import datetime
 
# using date.today() to get todays date
dateToday = datetime.date.today()
 
# Using toordinal() to generate ordinal value.
toOrdinal = dateToday.toordinal()
 
# Prints Ordinal Value of Todays Date.
print(f"Ordinal of date {dateToday} is {toOrdinal}")


Python3
# importing datetime class
from datetime import datetime
 
# Creating an instance of datetime.
dateIs = datetime(189, 0, 0)
 
# Using toordinal() method
toOrdinal = dateIs.toordinal()
print(f"Ordinal value of Earliest Datetime {dateIs} is {toOrdinal}")


Python3
# importing datetime class
from datetime import datetime
 
# Creating an instance of datetime.
dateIs = datetime(1, 1, 1, 0, 0, 0, 0)
 
# Using toordinal() method
toOrdinal = dateIs.toordinal()
print(f"Ordinal value of Earliest Datetime {dateIs} is {toOrdinal}")
 
print()
 
dateIs = datetime(9999, 12, 31, 23, 59, 59)
toOrdinal = dateIs.toordinal()
print(f"Ordinal value of Latemost Datetime {dateIs} is {toOrdinal}")


输出
Ordinal of date 2021-08-03 is 738005

注意: DateTime 类的属性应该在给定的范围内,否则会显示ValueError

示例 2:示例显示参数需要在范围内

蟒蛇3

# importing datetime class
from datetime import datetime
 
# Creating an instance of datetime.
dateIs = datetime(189, 0, 0)
 
# Using toordinal() method
toOrdinal = dateIs.toordinal()
print(f"Ordinal value of Earliest Datetime {dateIs} is {toOrdinal}")

输出:

示例 3:使用 datetime.toordinal()函数返回给定 DateTime 对象的公历序数。

蟒蛇3

# importing datetime class
from datetime import datetime
 
# Creating an instance of datetime.
dateIs = datetime(1, 1, 1, 0, 0, 0, 0)
 
# Using toordinal() method
toOrdinal = dateIs.toordinal()
print(f"Ordinal value of Earliest Datetime {dateIs} is {toOrdinal}")
 
print()
 
dateIs = datetime(9999, 12, 31, 23, 59, 59)
toOrdinal = dateIs.toordinal()
print(f"Ordinal value of Latemost Datetime {dateIs} is {toOrdinal}")

输出: