在Python中,你可以使用`datetime`模块来处理日期和时间,并使用`strftime`方法来格式化日期和时间。以下是一些常见的日期时间格式化示例:
1. 年月日时分秒:
```python
from datetime import datetime
获取当前时间
now = datetime.now()
格式化输出
formatted_time = now.strftime('%Y-%m-%d %H:%M:%S')
print(formatted_time) 输出类似 2024-05-21 14:23:45
2. 年月日:
```python
格式化输出
formatted_date = now.strftime('%Y-%m-%d')
print(formatted_date) 输出类似 2024-05-21
3. 月日年时分秒:
```python
格式化输出
formatted_time = now.strftime('%m/%d/%Y %H:%M:%S')
print(formatted_time) 输出类似 05/21/2024 14:23:45
4. 星期几的简写和全称:
```python
格式化输出
formatted_day_short = now.strftime('%a') 星期几的简写,如Mon
formatted_day_full = now.strftime('%A') 星期几的全称,如Monday
print(formatted_day_short) 输出类似Mon
print(formatted_day_full) 输出类似Monday
5. 月份和年份的简写和全称:
```python
格式化输出
formatted_month_short = now.strftime('%b') 月份的简写,如Jan
formatted_month_full = now.strftime('%B') 月份的全称,如January
formatted_year_short = now.strftime('%y') 两位数的年份表示,如20
formatted_year_full = now.strftime('%Y') 四位数的年份表示,如2024
print(formatted_month_short) 输出类似Jan
print(formatted_month_full) 输出类似January
print(formatted_year_short) 输出类似20
print(formatted_year_full) 输出类似2024
6. 12小时制的时间表示:
```python
格式化输出
formatted_time_12hr = now.strftime('%I:%M:%S %p')
print(formatted_time_12hr) 输出类似02:23:45 PM
以上格式化字符串中的`%`符号后面跟的格式代码对应于不同的日期时间部分,例如`%Y`代表四位数的年份,`%m`代表月份,`%d`代表月中的某一天,`%H`代表24小时制的小时数,`%M`代表分钟数,`%S`代表秒数,`%a`代表星期几的简写,`%A`代表星期几的全称,`%b`代表月份的简写,`%B`代表月份的全称,`%p`代表AM/PM。
你可以根据需要选择合适的格式化字符串来显示日期和时间