在本文中,我們將討論 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。