在Python中,`datetime`模块用于处理日期和时间。以下是一些基本用法:
导入模块
```python
from datetime import datetime
获取当前日期和时间
```python
now = datetime.now()
print(now)
根据指定日期和时间创建`datetime`对象
```python
dt = datetime.datetime(2022, 1, 1, 12, 0, 0)
print(dt)
获取`datetime`对象的年、月、日、时、分、秒等信息
```python
print(dt.year)
print(dt.month)
print(dt.day)
print(dt.hour)
print(dt.minute)
print(dt.second)
格式化日期和时间输出
```python
print(now.strftime('%Y-%m-%d %H:%M:%S'))
对日期和时间进行加减操作
```python
delta = datetime.timedelta(days=1)
one_day_later = now + delta
one_day_ago = now - delta
print(one_day_later)
print(one_day_ago)
获取当前日期
```python
today = datetime.date.today()
print(today)
创建日期对象
```python
date_obj = datetime.date(2023, 6, 6)
print(date_obj)
时间替换
```python
today_with_zero_minutes = today.replace(minute=0, second=0)
print(today_with_zero_minutes)
时间加减
```python
one_hour_later = today + datetime.timedelta(hours=1)
print(one_hour_later)
字符串转时间
```python
date_str = '2023-06-06'
date_obj = datetime.datetime.strptime(date_str, '%Y-%m-%d')
print(date_obj)
时间元组
```python
time_tuple = today.timetuple()
print(time_tuple)
日期时间格式转换
```python
formatted_date = today.strftime('%Y/%m/%d')
print(formatted_date)
以上是`datetime`模块的一些基本用法,您可以根据需要进一步探索模块中的其他功能。