datetime
module is a module in the Python standard library for working with dates and times. It provides various classes and functions that enable us to create, manipulate and format dates, times and datetime objects. The following isdatetime
a detailed explanation and usage instructions of some common classes and functions of the module:
1. date
Class: An object representing a date, including year, month, and day.
- Create date object:
import datetime
# 创建日期对象
date_obj = datetime.date(year, month, day)
- Get the current date:
current_date = datetime.date.today()
- Date properties and methods:
year = date_obj.year
month = date_obj.month
day = date_obj.day
iso_weekday = date_obj.isoweekday() # 返回星期几,星期一为1,星期日为7
2. time
Class: Object representing time, including hours, minutes, seconds, and microseconds.
- Create time object:
import datetime
# 创建时间对象
time_obj = datetime.time(hour, minute, second, microsecond)
- Time properties and methods:
hour = time_obj.hour
minute = time_obj.minute
second = time_obj.second
microsecond = time_obj.microsecond
3. datetime
Class: Object representing date and time, including year, month, day, hour, minute, second and microsecond.
- Create datetime object:
import datetime
# 创建日期时间对象
datetime_obj = datetime.datetime(year, month, day, hour, minute, second, microsecond)
- Get the current date and time:
current_datetime = datetime.datetime.now()
- Datetime properties and methods:
year = datetime_obj.year
month = datetime_obj.month
day = datetime_obj.day
hour = datetime_obj.hour
minute = datetime_obj.minute
second = datetime_obj.second
microsecond = datetime_obj.microsecond
4. Format date and time as strings:
formatted_date = date_obj.strftime(format)
formatted_time = time_obj.strftime(format)
formatted_datetime = datetime_obj.strftime(format)
5. Parse the string into a date or time object:
parsed_date = datetime.datetime.strptime(date_string, format)
parsed_time = datetime.datetime.strptime(time_string, format).time()
6. Calculate and operate date and time:
import datetime
# 日期操作
new_date = date_obj + datetime.timedelta(days=1)
# 时间操作
new_time = time_obj + datetime.timedelta(hours=1)
The above are datetime
some common uses and functions of modules. Using these classes and functions, you can easily handle dates and times. For more details and usage of other functions, please refer to datetime
the section on modules in the official Python documentation