There are many excellent calendar libraries and date libraries in Python for us to use. These libraries can help us handle date and calendar related operations. Next, I will introduce you to several common choices and provide corresponding code examples.
import datetime # 获取当前日期和时间 now = datetime.datetime.now() print("当前日期和时间:", now) # 获取当前日期 date = datetime.date.today() print("当前日期:", date) # 格式化日期 formatted_date = now.strftime("%Y-%m-%d %H:%M:%S") print("格式化后的日期:", formatted_date) # 计算日期差 date1 = datetime.date(2021, 1, 1) date2 = datetime.date(2021, 12, 31) delta = date2 - date1 print("日期差:", delta.days)
import calendar # 打印某年的日历 year = 2022 print(calendar.calendar(year)) # 打印某月的日历 year = 2022 month = 1 print(calendar.month(year, month)) # 判断是否是闰年 year = 2022 is_leap = calendar.isleap(year) if is_leap: print(year, "是闰年") else: print(year, "不是闰年") # 计算某个月的第一天是星期几 year = 2022 month = 1 _, first_day = calendar.monthrange(year, month) print("第一天是星期:", first_day)
import arrow # 获取当前时间 now = arrow.now() print("当前时间:", now) # 获取当前日期 date = arrow.now().date() print("当前日期:", date) # 格式化日期 formatted_date = now.format('YYYY-MM-DD HH:mm:ss') print("格式化后的日期:", formatted_date) # 计算日期差 date1 = arrow.get('2021-01-01') date2 = arrow.get('2021-12-31') delta = (date2 - date1).days print("日期差:", delta)
The above are several commonly used Python calendar libraries and date libraries. According to different needs, we can choose a suitable library to handle date and calendar related operations. I hope the above content is helpful to everyone!
The above is the detailed content of What are the options for calendar and date libraries in Python?. For more information, please follow other related articles on the PHP Chinese website!