共計 1265 個字符,預計需要花費 4 分鐘才能閱讀完成。
datetime.date 是 python 中的一個類,用于表示日期。它的常用方法和屬性有:
- today():返回當前日期。
- fromisoformat(date_string):從字符串中解析日期。
- year:返回年份。
- month:返回月份。
- day:返回日期。
- isoformat():返回日期的 ISO 格式字符串(YYYY-MM-DD)。
- strftime(format):將日期格式化為指定的字符串格式。
- replace(year, month, day):返回一個新的日期對象,替換指定的年、月、日。
- weekday():返回星期幾(0 表示星期一,6 表示星期日)。
- isoweekday():返回星期幾(1 表示星期一,7 表示星期日)。
- isocalendar():返回一個包含 ISO 年份、ISO 周數和 ISO 工作日的元組。
- timetuple():返回日期的 time.struct_time 對象。
- toordinal():返回自公元 1 年 1 月 1 日以來的天數。
下面是一些示例使用 datetime.date 的代碼:
import datetime
# 獲取當前日期
today = datetime.date.today()
print(today)
# 解析日期字符串
date_str = '2022-10-31'
date = datetime.date.fromisoformat(date_str)
print(date)
# 獲取年、月、日
year = date.year
month = date.month
day = date.day
print(year, month, day)
# 將日期格式化為字符串
formatted_date = date.strftime('%Y/%m/%d')
print(formatted_date)
# 替換年份
new_date = date.replace(year=2023)
print(new_date)
# 獲取星期幾
weekday = date.weekday()
print(weekday)
# 獲取 ISO 年份、ISO 周數和 ISO 工作日
iso_year, iso_week, iso_weekday = date.isocalendar()
print(iso_year, iso_week, iso_weekday)
# 獲取日期的 time.struct_time 對象
time_tuple = date.timetuple()
print(time_tuple)
# 獲取自公元 1 年 1 月 1 日以來的天數
ordinal = date.toordinal()
print(ordinal)
輸出結果:
2022-11-09
2022-10-31
2022 10 31
2022/10/31
2023-10-31
0
2022 44 1
time.struct_time(tm_year=2022, tm_mon=10, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=304, tm_isdst=-1)
738053
丸趣 TV 網 – 提供最優質的資源集合!
正文完