Python datetime.date Usage Guide
datetime.date is a class in Python used to represent dates. Its common methods and properties include:
- today(): Returns the current date.
- Parse a date from a string using fromisoformat(date_string).
- year: return the year.
- Month: returns the month.
- Day: Get the date.
- isoformat() returns a string of the date in ISO format (YYYY-MM-DD).
- strftime(format): Formats the date into the specified string format.
- replace(year, month, day):Creates a new date object with the specified year, month, and day.
- weekday() returns the day of the week (0 represents Monday, 6 represents Sunday).
- isoweekday() function: returns the day of the week (1 for Monday, 7 for Sunday).
- isocalendar(): return a tuple containing the ISO year, ISO week number, and ISO weekday.
- timetuple(): Returns a time.struct_time object for the date.
- toordinal(): returns the number of days since January 1, 1 AD.
Here are some code examples using 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)
The output result:
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