Python日期处理:获取年、月、日、星期等30种信息

作者:da吃一鲸8862024.01.17 20:45浏览量:16

简介:在Python中,我们可以使用datetime模块来处理日期和时间。这个模块提供了许多有用的类和函数,可以帮助我们获取和处理日期和时间信息。下面是一个简单的例子,演示如何使用datetime模块从日期中获取年、月、日、星期等30种信息。

在Python中,我们可以通过datetime模块的datetime类来处理日期和时间。datetime类具有许多属性和方法,可以用于获取日期和时间的各种信息。
下面是一个简单的例子,演示如何使用datetime类从日期中获取年、月、日、星期等30种信息:
```python
from datetime import datetime

获取当前日期和时间

now = datetime.now()

获取年、月、日、星期等30种信息

year = now.year
month = now.month
day = now.day
weekday = now.strftime(‘%A’) # 星期几,例如Monday, Tuesday等
weekday_number = now.weekday() # 星期几的数字表示,例如0表示星期一,6表示星期日
hour = now.hour
minute = now.minute
second = now.second
microsecond = now.microsecond # 微秒数
day_of_year = now.timetuple().tm_yday # 一年中的第几天
quarter = now.month // 3 + 1 # 一年中的第几季度
week_of_year = now.isocalendar()[1] # 一年中的第几周
century = now.strftime(‘%Y’)[:2] + ‘00’ # 世纪,例如20世纪表示为2000年
decade = (now.year // 10) * 10 # 十年,例如2020年表示为2000年代
era = now.strftime(‘%B’) # 世纪纪元,例如公元表示为AD,公元前表示为BC
date_string = now.strftime(‘%Y-%m-%d’) # 日期字符串,例如2023-07-19
time_string = now.strftime(‘%H:%M:%S’) # 时间字符串,例如14:30:45
full_date_string = now.strftime(‘%A, %B %d, %Y’) # 完整日期字符串,例如Monday, July 19, 2023
full_time_string = now.strftime(‘%I:%M %p, %A %B %d %Y’) # 完整时间字符串,例如02:30 PM, Monday July 19 2023
am_or_pm = now.strftime(‘%p’) # 上午或下午,例如AM或PM
period_of_day = now.strftime(‘%p’) # 上午或下午,与am_or_pm相同
zone_offset = now.strftime(‘%z’) # 时区偏移量,例如+0800或-0630
daylight_saving_offset = now.strftime(‘%Z’) # 夏令时偏移量,例如EDT或EST等时区缩写
month_name = now.strftime(‘%B’) # 月份名称,例如January, February等
quarter_name = now.strftime(‘%b’) # 月份缩写,例如Jan, Feb等
short_month_name = now.strftime(‘%b’) # 月份缩写(与quarter_name相同)
short_quarter_name = now.strftime(‘%b’) # 季度缩写(与quarter_name相同)
time_zone_name = now.strftime(‘%Z’) # 时区名称,例如UTC或EST等时区缩写
short_time_zone_name = now.strftime(‘%z’) # 时区缩写(与time_zone_name相同)