在本文中,我们将讨论 DateTime 模块中的 weekday() 函数。 weekday() 函数用于根据给定的 DateTime 获取周数。它将返回 0-6 范围内的数字表示 意义 0 Monday 1 Tuesday 2 Wednesday 3 Thursday 4 Friday 5 Saturday 6 Sunday
它将以“(YYYY, MM, DD, HH, MM, SS)”的格式将输入作为DateTime,其中,
- YYYY 代表年份
- MM 代表月
- DD 代表日期
- HH 代表小时
- MM代表分钟
- SS 代表秒
我们首先需要导入 DateTime 模块并创建一个 DateTime,现在使用 weekday() 函数我们将获得特定 DateTime 的工作日。
用法:
datetime(YYYY,MM,DD, HH,MM,SS).weekday()
我们还可以使用以下语法从 DateTime 中提取日期:
用法:
datetime(YYYY,MM,DD, HH,MM,SS).date()
示例:Python程序来创建DateTime并显示DateTime和日期
Python3
# importing datetime class
from datetime import datetime
# create datetime
x = datetime(2021, 8, 8, 12, 5, 6)
# display
print("Datetime is:", x)
# get the date
print("Date is:", x.date())
输出:
Datetime is:2021-08-08 12:05:06
Date is:2021-08-08
例:用于获取给定日期时间的工作日的 Python 程序
Python3
# importing datetime class
from datetime import datetime
# create datetime
x = datetime(2021, 8, 8, 12, 5, 6)
# display
print("Datetime is:", x)
# get the weekday
print("weekday is:", x.weekday())
# create datetime
x = datetime(2021, 9, 10, 12, 5, 6)
# display
print("Datetime is:", x)
# get the weekday
print("weekday is:", x.weekday())
# create datetime
x = datetime(2020, 1, 8, 12, 5, 6)
# display
print("Datetime is:", x)
# get the weekday
print("weekday is:", x.weekday())
输出:
Datetime is:2021-08-08 12:05:06
weekday is:6
Datetime is:2021-09-10 12:05:06
weekday is:4
Datetime is:2020-01-08 12:05:06
weekday is:2
范例3:获取工作日名称的Python程序
Python3
# create a list of weekdays
from datetime import datetime
days = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"]
# importing datetime class
# create datetime
x = datetime(2021, 8, 8, 12, 5, 6)
# display
print("Datetime is:", x)
# get the weekday name using index
print("weekday is:", days[x.weekday()])
# create datetime
x = datetime(2021, 9, 10, 12, 5, 6)
# display
print("Datetime is:", x)
# get the weekday name using index
print("weekday is:", days[x.weekday()])
# create datetime using index
x = datetime(2020, 1, 8, 12, 5, 6)
# display
print("Datetime is:", x)
# get the weekday name using index
print("weekday is:", days[x.weekday()])
输出:
Datetime is:2021-08-08 12:05:06
weekday is:Sunday
Datetime is:2021-09-10 12:05:06
weekday is:Friday
Datetime is:2020-01-08 12:05:06
weekday is:Wednesday
相关用法
- Python Pandas PeriodIndex.weekday用法及代码示例
- Python Pandas DatetimeIndex.weekday用法及代码示例
- Python Pandas Period.weekday用法及代码示例
- Python Pandas Timestamp.weekday用法及代码示例
- Python Pandas Series.dt.weekday用法及代码示例
- Python datetime.timetz()用法及代码示例
- Python datetime.utcoffset()用法及代码示例
- Python datetime.tzname()用法及代码示例
- Python DateTime astimezone()用法及代码示例
注:本文由纯净天空筛选整理自sravankumar8128大神的英文原创作品 Python DateTime weekday() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。