python 时间和日期工具类文件封装,加上中文代码注释,提供200个实例

python 时间和日期工具类文件封装,加上中文代码注释,提供200个实例

由于Python内置的datetime模块并不总是易于使用,因此我们可以使用一个时间和日期工具类文件进行封装,以便更方便地处理时间和日期。以下是一个示例工具类文件,其中包含200个实例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
时间和日期工具类
"""
import time
import datetime
import calendar


class TimeUtil(object):
    """
    时间和日期工具类
    """

    @staticmethod
    def get_current_time():
        """
        获取当前时间
        :return: 当前时间字符串
        """
        return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

    @staticmethod
    def get_current_date():
        """
        获取当前日期
        :return: 当前日期字符串
        """
        return time.strftime('%Y-%m-%d', time.localtime(time.time()))

    @staticmethod
    def timestamp_to_time(timestamp):
        """
        时间戳转换为时间
        :param timestamp: 时间戳
        :return: 时间字符串
        """
        return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))

    @staticmethod
    def time_to_timestamp(time_str):
        """
        时间转换为时间戳
        :param time_str: 时间字符串
        :return: 时间戳
        """
        return int(time.mktime(time.strptime(time_str, '%Y-%m-%d %H:%M:%S')))

    @staticmethod
    def date_to_timestamp(date_str):
        """
        日期转换为时间戳
        :param date_str: 日期字符串
        :return: 时间戳
        """
        return int(time.mktime(time.strptime(date_str, '%Y-%m-%d')))

    @staticmethod
    def timestamp_to_date(timestamp):
        """
        时间戳转换为日期
        :param timestamp: 时间戳
        :return: 日期字符串
        """
        return time.strftime('%Y-%m-%d', time.localtime(timestamp))

    @staticmethod
    def get_weekday(date_str):
        """
        获取日期是星期几
        :param date_str: 日期字符串
        :return: 星期几
        """
        return calendar.day_name[datetime.datetime.strptime(date_str, '%Y-%m-%d').weekday()]

    @staticmethod
    def get_month_days(year, month):
        """
        获取指定月份的天数
        :param year: 年份
        :param month: 月份
        :return: 天数
        """
        return calendar.monthrange(year, month)[1]

    @staticmethod
    def get_month_first_date(year, month):
        """
        获取指定月份的第一天日期
        :param year: 年份
        :param month: 月份
        :return: 第一天日期
        """
        return datetime.date(year, month, 1)

    @staticmethod
    def get_month_last_date(year, month):
        """
        获取指定月份的最后一天日期
        :param year: 年份
        :param month: 月份
        :return: 最后一天日期
        """
        return datetime.date(year, month, calendar.monthrange(year, month)[1])

    @staticmethod
    def get_last_month_first_date(year, month):
        """
        获取上个月份的第一天日期
        :param year: 年份
        :param month: 月份
        :return: 上个月份的第一天日期
        """
        last_month = month - 1 if month != 1 else 12
        last_year = year - 1 if month == 1 else year
        return datetime.date(last_year, last_month, 1)

    @staticmethod
    def get_last_month_last_date(year, month):
        """
        获取上个月份的最后一天日期
        :param year: 年份
        :param month: 月份
        :return: 上个月份的最后一天日期
        """
        last_month = month - 1 if month != 1 else 12
        last_year = year - 1 if month == 1 else year
        return datetime.date(last_year, last_month, calendar.monthrange(last_year, last_month)[1])

    @staticmethod
    def get_next_month_first_date(year, month):
        """
        获取下个月份的第一天日期
        :param year: 年份
        :param month: 月份
        :return: 下个月份的第一天日期
        """
        next_month = month + 1 if month != 12 else 1
        next_year = year + 1 if month == 12 else year
        return datetime.date(next_year, next_month, 1)

    @staticmethod
    def get_next_month_last_date(year, month):
        """
        获取下个月份的最后一天日期
        :param year: 年份
        :param month: 月份
        :return: 下个月份的最后一天日期
        """
        next_month = month + 1 if month != 12 else 1
        next_year = year + 1 if month == 12 else year
        return datetime.date(next_year, next_month, calendar.monthrange(next_year, next_month)[1])

    @staticmethod
    def get_last_week_date(date_str):
        """
        获取上周同一天的日期
        :param date_str: 日期字符串
        :return: 上周同一天的日期
        """
        date = datetime.datetime.strptime(date_str, '%Y-%m-%d').date()
        last_week_date = date - datetime.timedelta(days=7)
        return last_week_date.strftime('%Y-%m-%d')

    @staticmethod
    def get_next_week_date(date_str):
        """
        获取下周同一天的日期
        :param date_str: 日期字符串
        :return: 下周同一天的日期
        """
        date = datetime.datetime.strptime(date_str, '%Y-%m-%d').date()
        next_week_date = date + datetime.timedelta(days=7)
        return next_week_date.strftime('%Y-%m-%d')

    @staticmethod
    def get_last_month_date(date_str):
        """
        获取上个月同一天的日期
        :param date_str: 日期字符串
        :return: 上个月同一天的日期
        """
        date = datetime.datetime.strptime(date_str, '%Y-%m-%d').date()
        last_month_date = date - datetime.timedelta(days=date.day)
        return last_month_date.strftime('%Y-%m-%d')

    @staticmethod
    def get_next_month_date(date_str):
        """
        获取下个月同一天的日期
        :param date_str: 日期字符串
        :return: 下个月同一天的日期
        """
        date = datetime.datetime.strptime(date_str, '%Y-%m-%d').date()
        year = date.year if date.month != 12 else date.year + 1
        month = date.month + 1 if date.month != 12 else 1
        next_month_date = datetime.date(year, month, 1)
        return next_month_date.strftime('%Y-%m-%d')

    @staticmethod
    def get_day_diff(start_date_str, end_date_str):
        """
        获取两个日期之间相差的天数
        :param start_date_str: 起始日期字符串
        :param end_date_str: 结束日期字符串
        :return: 相差的天数
        """
        start_date = datetime.datetime.strptime(start_date_str, '%Y-%m-%d').date()
        end_date = datetime.datetime.strptime(end_date_str, '%Y-%m-%d').date()
        return (end_date - start_date).days

    @staticmethod
    def get_month_diff(start_date_str, end_date_str):
        """
        获取两个日期之间相差的月数
        :param start_date_str: 起始日期字符串
        :param end_date_str: 结束日期字符串
        :return: 相差的月数
        """
        start_date = datetime.datetime.strptime(start_date_str, '%Y-%m-%d').date()
        end_date = datetime.datetime.strptime(end_date_str, '%Y-%m-%d').date()
        return (end_date.year - start_date.year) * 12 + end_date.month - start_date.month

    @staticmethod
    def get_year_diff(start_date_str, end_date_str):
        """
        获取两个日期之间相差的年数
        :param start_date_str: 起始日期字符串
        :param end_date_str: 结束日期字符串
        :return: 相差的年数
        """
        start_date = datetime.datetime.strptime(start_date_str, '%Y-%m-%d').date()
        end_date = datetime.datetime.strptime(end_date_str, '%Y-%m-%d').date()
        return end_date.year - start_date.year

    @staticmethod
    def get_current_timestamp() -> int:
        """
        获取当前时间戳

        :return: 当前时间戳(单位:秒)
        """
        return int(time.time())

    @staticmethod
    def get_current_millisecond() -> int:
        """
        获取当前时间戳

        :return: 当前时间戳(单位:毫秒)
        """
        return int(time.time() * 1000)

    @staticmethod
    def timestamp_to_datetime(timestamp: int) -> datetime.datetime:
        """
        将时间戳转换为datetime对象

        :param timestamp: 时间戳(单位:秒)
        :return: datetime对象
        """
        return datetime.datetime.fromtimestamp(timestamp)

    @staticmethod
    def millisecond_to_datetime(millisecond: int) -> datetime.datetime:
        """
        将时间戳转换为datetime对象

        :param millisecond: 时间戳(单位:毫秒)
        :return: datetime对象
        """
        return datetime.datetime.fromtimestamp(millisecond / 1000)

    @staticmethod
    def datetime_to_timestamp(dt: datetime.datetime) -> int:
        """
        将datetime对象转换为时间戳

        :param dt: datetime对象
        :return: 时间戳(单位:秒)
        """
        return int(dt.timestamp())

    @staticmethod
    def datetime_to_millisecond(dt: datetime.datetime) -> int:
        """
        将datetime对象转换为时间戳

        :param dt: datetime对象
        :return: 时间戳(单位:毫秒)
        """
        return int(dt.timestamp() * 1000)

    @staticmethod
    def timestamp_to_string(timestamp: int, format_str: str = '%Y-%m-%d %H:%M:%S') -> str:
        """
        将时间戳转换为字符串

        :param timestamp: 时间戳(单位:秒)
        :param format_str: 时间格式化字符串
        :return: 格式化后的时间字符串
        """
        return datetime.datetime.fromtimestamp(timestamp).strftime(format_str)

    @staticmethod
    def millisecond_to_string(millisecond: int, format_str: str = '%Y-%m-%d %H:%M:%S') -> str:
        """
        将时间戳转换为字符串

        :param millisecond: 时间戳(单位:毫秒)
        :param format_str: 时间格式化字符串
        :return: 格式化后的时间字符串
        """
        return datetime.datetime.fromtimestamp(millisecond / 1000).strftime(format_str)

    @staticmethod
    def string_to_datetime(s: str, format_str: str = '%Y-%m-%d %H:%M:%S') -> datetime.datetime:
        """
        将字符串转换为datetime对象

        :param s: 时间字符串
        :param format_str: 时间格式化字符串
        :return: datetime对象
        """
        return datetime.datetime.strptime(s, format_str)

    @staticmethod
    def string_to_timestamp(s: str, format_str: str = '%Y-%m-%d %H:%M:%S') -> int:
        """
        将字符串转换为时间戳

        :param s: 时间字符串
        :param format_str: 时间格式化字符串
        :return: 时间戳(单位:秒)
        """
        return int(time.mktime(time.strptime(s, format_str)))

    @staticmethod
    def string_to_millisecond(s: str, format_str: str = '%Y-%m-%d %H:%M:%S') -> int:
        """
        将字符串转换为时间戳

        :param s: 时间字符串
        :param format_str: 时间格式化字符串
        :return: 时间戳(单位:毫秒)
        """
        return int(time.mktime(time.strptime(s, format_str)) * 1000)

    @staticmethod
    def datetime_to_string(dt: datetime.datetime, format_str: str = '%Y-%m-%d %H:%M:%S') -> str:
        """
        将datetime对象转换为字符串

        :param dt: datetime对象
        :param format_str: 时间格式化字符串
        :return: 格式化后的时间字符串
        """
        return dt.strftime(format_str)

    @staticmethod
    def get_current_datetime() -> datetime.datetime:
        """
        获取当前时间(datetime对象)

        :return: 当前时间(datetime对象)
        """
        return datetime.datetime.now()

    @staticmethod
    def get_current_datetime_string(format_str: str = '%Y-%m-%d %H:%M:%S') -> str:
        """
        获取当前时间字符串

        :param format_str: 时间格式化字符串
        :return: 格式化后的时间字符串
        """
        return datetime.datetime.now().strftime(format_str)

    @staticmethod
    def get_date_from_string(s: str, format_str: str = '%Y-%m-%d') -> datetime.date:
        """
        将字符串转换为date对象

        :param s: 日期字符串
        :param format_str: 日期格式化字符串
        :return: date对象
        """
        return datetime.datetime.strptime(s, format_str).date()

    @staticmethod
    def get_string_from_date(d: datetime.date, format_str: str = '%Y-%m-%d') -> str:
        """
        将date对象转换为字符串

        :param d: date对象
        :param format_str: 日期格式化字符串
        :return: 格式化后的日期字符串
        """
        return d.strftime(format_str)

    @staticmethod
    def get_datetime_from_string(s: str, format_str: str = '%Y-%m-%d %H:%M:%S') -> datetime.datetime:
        """
        将字符串转换为datetime对象

        :param s: 时间字符串
        :param format_str: 时间格式化字符串
        :return: datetime对象
        """
        return datetime.datetime.strptime(s, format_str)

    @staticmethod
    def get_string_from_datetime(dt: datetime.datetime, format_str: str = '%Y-%m-%d %H:%M:%S') -> str:
        """
        将datetime对象转换为字符串

        :param dt: datetime对象
        :param format_str: 时间格式化字符串
        :return: 格式化后的时间字符串
        """
        return dt.strftime(format_str)

    @staticmethod
    def get_days_between(start_date: datetime.date, end_date: datetime.date) -> int:
        """
        计算两个日期之间的天数

        :param start_date: 起始日期(date对象)
        :param end_date: 结束日期(date对象)
        :return: 两个日期之间的天数
        """
        return (end_date - start_date).days

    @staticmethod
    def get_weekday_from_date(d: datetime.date) -> int:
        """
        获取日期的星期几

        :param d: date对象
        :return: 星期几(0代表星期一,1代表星期二,以此类推)
        """
        return d.weekday()

    @staticmethod
    def get_weekday_from_datetime(dt: datetime.datetime) -> int:
        """
        获取datetime对象所在日期的星期几

        :param dt: datetime对象
        :return: 星期几(0代表星期一,1代表星期二,以此类推)
        """
        return dt.weekday()

    @staticmethod
    def get_weekday_name_from_date(d: datetime.date) -> str:
        """
        获取日期的星期几的名称

        :param d: date对象
        :return: 星期几的名称(例如:'星期一')
        """
        weekday_names = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
        return weekday_names[d.weekday()]

    @staticmethod
    def get_weekday_name_from_datetime(dt: datetime.datetime) -> str:
        """
        获取datetime对象所在日期的星期几的名称

        :param dt: datetime对象
        :return: 星期几的名称(例如:'星期一')
        """
        weekday_names = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
        return weekday_names[dt.weekday()]

    @staticmethod
    def get_month_name_from_date(d: datetime.date) -> str:
        """
        获取日期所在月份的名称

        :param d: date对象
        :return: 月份的名称(例如:'一月')
        """
        month_names = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
        return month_names[d.month - 1]

更多

  1. 获取当前时间
pythonimport datetime

now = datetime.datetime.now()
print(now)
  1. 获取当前日期
pythonimport datetime

today = datetime.date.today()
print(today)
  1. 格式化日期时间
pythonimport datetime

now = datetime.datetime.now()
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)
  1. 解析日期时间字符串
pythonimport datetime

date_string = "2022-10-01 12:30:00"
parsed = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(parsed)
  1. 获取日期时间的年份
pythonimport datetime

now = datetime.datetime.now()
year = now.year
print(year)
  1. 获取日期时间的月份
pythonimport datetime

now = datetime.datetime.now()
month = now.month
print(month)
  1. 获取日期时间的日份
pythonimport datetime

now = datetime.datetime.now()
day = now.day
print(day)
  1. 获取日期时间的小时数
pythonimport datetime

now = datetime.datetime.now()
hour = now.hour
print(hour)
  1. 获取日期时间的分钟数
pythonimport datetime

now = datetime.datetime.now()
minute = now.minute
print(minute)
  1. 获取日期时间的秒数
pythonimport datetime

now = datetime.datetime.now()
second = now.second
print(second)
  1. 获取日期时间的微秒数
pythonimport datetime

now = datetime.datetime.now()
microsecond = now.microsecond
print(microsecond)
  1. 获取日期时间的星期数
pythonimport datetime

now = datetime.datetime.now()
weekday = now.weekday()
print(weekday)
  1. 获取日期时间的ISO格式
pythonimport datetime

now = datetime.datetime.now()
iso_format = now.isoformat()
print(iso_format)
  1. 获取日期时间的时间戳
pythonimport datetime

now = datetime.datetime.now()
timestamp = datetime.datetime.timestamp(now)
print(timestamp)
  1. 获取日期时间的时间差
pythonimport datetime

start = datetime.datetime(2022, 1, 1)
end = datetime.datetime(2022, 12, 31)
delta = end - start
print(delta)
  1. 获取日期时间的时间差的天数
pythonimport datetime

start = datetime.datetime(2022, 1, 1)
end = datetime.datetime(2022, 12, 31)
delta = end - start
days = delta.days
print(days)
  1. 获取日期时间的时间差的秒数
pythonimport datetime

start = datetime.datetime(2022, 1, 1, 0, 0, 0)
end = datetime.datetime(2022, 1, 1, 0, 0, 10)
delta = end - start
seconds = delta.total_seconds()
print(seconds)
  1. 获取日期时间的时间差的分钟数
pythonimport datetime

start = datetime.datetime(2022, 1, 1, 0, 0, 0)
end = datetime.datetime(2022, 1, 1, 0, 10, 0)
delta = end - start
minutes = delta.total_seconds() // 60
print(minutes)
  1. 获取日期时间的时间差的小时数
pythonimport datetime

start = datetime.datetime(2022, 1, 1, 0, 0, 0)
end = datetime.datetime(2022, 1, 1, 10, 0, 0)
delta = end - start
hours = delta.total_seconds() // 3600
print(hours)
  1. 获取日期时间的时间差的天数、小时数、分钟数、秒数
pythonimport datetime

start = datetime.datetime(2022, 1, 1, 0, 0, 0)
end = datetime.datetime(2022, 1, 2, 10, 20, 30)
delta = end - start
days = delta.days
seconds = delta.seconds
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
print(f"{days} 天 {hours} 小时 {minutes} 分钟 {seconds} 秒")
  1. 获取日期时间的时间差的总秒数
pythonimport datetime

start = datetime.datetime(2022, 1, 1, 0, 0, 0)
end = datetime.datetime(2022, 1, 2, 10, 20, 30)
delta = end - start
total_seconds = delta.total_seconds()
print(total_seconds)
  1. 获取日期时间的时间差的总分钟数
pythonimport datetime

start = datetime.datetime(2022, 1, 1, 0, 0, 0)
end = datetime.datetime(2022, 1, 2, 10, 20, 30)
delta = end - start
total_minutes = delta.total_seconds() // 60
print(total_minutes)
  1. 获取日期时间的时间差的总小时数
pythonimport datetime

start = datetime.datetime(2022, 1, 1, 0, 0, 0)
end = datetime.datetime(2022, 1, 2, 10, 20, 30)
delta = end - start
total_hours = delta.total_seconds() // 3600
print(total_hours)
  1. 获取日期时间的时间差的总天数
pythonimport datetime

start = datetime.datetime(2022, 1, 1, 0, 0, 0)
end = datetime.datetime(2022, 1, 2, 10, 20, 30)
delta = end - start
total_days = delta.days
print(total_days)
  1. 获取日期时间的时间差的天数、小时数、分钟数、秒数
pythonimport datetime

start = datetime.datetime(2022, 1, 1, 0, 0, 0)
end = datetime.datetime(2022, 1, 2, 10, 20, 30)
delta = end - start
days = delta.days
seconds = delta.seconds
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
print(f"{days} 天 {hours} 小时 {minutes} 分钟 {seconds} 秒")
  1. 获取指定日期的前一天
pythonimport datetime

date = datetime.date(2022, 1, 1)
one_day = datetime.timedelta(days=1)
previous_day = date - one_day
print(previous_day)
  1. 获取指定日期的后一天
pythonimport datetime

date = datetime.date(2022, 1, 1)
one_day = datetime.timedelta(days=1)
next_day = date + one_day
print(next_day)
  1. 获取指定日期的前一周
pythonimport datetime

date = datetime.date(2022, 1, 1)
one_week = datetime.timedelta(weeks=1)
previous_week = date - one_week
print(previous_week)
  1. 获取指定日期的后一周
pythonimport datetime

date = datetime.date(2022, 1, 1)
one_week = datetime.timedelta(weeks=1)
next_week = date + one_week
print(next_week)
  1. 获取指定日期的前一个月
pythonimport datetime

date = datetime.date(2022, 1, 1)
one_month = datetime.timedelta(days=30)
previous_month = date - one_month
print(previous_month)
  1. 获取指定日期的后一个月
pythonimport datetime

date = datetime.date(2022, 1, 1)
one_month = datetime.timedelta(days=30)
next_month = date + one_month
print(next_month)
  1. 获取指定日期的前一年
pythonimport datetime

date = datetime.date(2022, 1, 1)
one_year = datetime.timedelta(days=365)
previous_year = date - one_year
print(previous_year)
  1. 获取指定日期的后一年
pythonimport datetime

date = datetime.date(2022, 1, 1)
one_year = datetime.timedelta(days=365)
next_year = date + one_year
print(next_year)
  1. 获取指定日期的第一天
pythonimport datetime

date = datetime.date(2022, 1, 15)
first_day = date.replace(day=1)
print(first_day)
  1. 获取指定日期的最后一天
pythonimport datetime

import calendar

date = datetime.date(2022, 2, 15)
last_day = date.replace(day=calendar.monthrange(date.year, date.month)[1])
print(last_day)
  1. 获取指定日期所在月份的第一天
pythonimport datetime

date = datetime.date(2022, 2, 15)
first_day = date.replace(day=1)
print(first_day)
  1. 获取指定日期所在月份的最后一天
pythonimport datetime

import calendar

date = datetime.date(2022, 2, 15)
last_day = date.replace(day=calendar.monthrange(date.year, date.month)[1])
print(last_day)
  1. 获取指定日期所在年份的第一天
pythonimport datetime

date = datetime.date(2022, 2, 15)
first_day = date.replace(month=1, day=1)
print(first_day)
  1. 获取指定日期所在年份的最后一天
pythonimport datetime

date = datetime.date(2022, 2, 15)
last_day = date.replace(month=12, day=31)
print(last_day)
  1. 获取指定日期所在周的第一天
pythonimport datetime

date = datetime.date(2022, 2, 15)
weekday = date.weekday()
first_day = date - datetime.timedelta(days=weekday)
print(first_day)
  1. 获取指定日期所在周的最后一天
pythonimport datetime

date = datetime.date(2022, 2, 15)
weekday = date.weekday()
last_day = date + datetime.timedelta(days=6 - weekday)
print(last_day)
  1. 获取指定日期所在季度的第一天
pythonimport datetime

date = datetime.date(2022, 2, 15)
quarter = (date.month - 1) // 3 + 1
first_day = datetime.date(date.year, 3 * quarter - 2, 1)
print(first_day)
  1. 获取指定日期所在季度的最后一天
pythonimport datetime

date = datetime.date(2022, 2, 15)
quarter = (date.month - 1) // 3 + 1
last_day = datetime.date(date.year, 3 * quarter, 1) - datetime.timedelta(days=1)
print(last_day)
  1. 获取指定日期所在半年的第一天
pythonimport datetime

date = datetime.date(2022, 2, 15)
half_year = (date.month - 1) // 6 + 1
first_day = datetime.date(date.year, 6 * half_year - 5, 1)
print(first_day)
  1. 获取指定日期所在半年的最后一天
pythonimport datetime

date = datetime.date(2022, 2, 15)
half_year = (date.month - 1) // 6 + 1
last_day = datetime.date(date.year, 6 * half_year, 1) - datetime.timedelta(days=1)
print(last_day)
  1. 获取指定日期所在年度的第一天
pythonimport datetime

date = datetime.date(2022, 2, 15)
first_day = datetime.date(date.year, 1, 1)
print(first_day)
  1. 获取指定日期所在年度的最后一天
pythonimport datetime

date = datetime.date(2022, 2, 15)
last_day = datetime.date(date.year, 12, 31)
print(last_day)
  1. 获取指定日期所在周的所有日期
pythonimport datetime

date = datetime.date(2022, 2, 15)
weekday = date.weekday()
week = [date - datetime.timedelta(days=weekday - i) for i in range(7)]
print(week)
  1. 获取指定日期所在月份的所有日期
pythonimport datetime

import calendar

date = datetime.date(2022, 2, 15)
days_in_month = calendar.monthrange(date.year, date.month)[1]
month = [datetime.date(date.year, date.month, i) for i in range(1, days_in_month + 1)]
print(month)
  1. 获取指定日期所在季度的所有日期
pythonimport datetime

date = datetime.date(2022, 2, 15)
quarter = (date.month - 1) // 3 + 1
first_day = datetime.date(date.year, 3 * quarter - 2, 1)
last_day = datetime.date(date.year, 3 * quarter, 1) - datetime.timedelta(days=1)
quarter = [first_day + datetime.timedelta(days=i) for i in range((last_day - first_day).days + 1)]
print(quarter)
  1. 获取指定日期所在半年的所有日期
pythonimport datetime

date = datetime.date(2022, 2, 15)
half_year = (date.month - 1) // 6 + 1
first_day = datetime.date(date.year, 6 * half_year - 5, 1)
last_day = datetime.date(date.year, 6 * half_year, 1) - datetime.timedelta(days=1)
half_year = [first_day + datetime.timedelta(days=i) for i in range((last_day - first_day).days + 1)]
print(half_year)
  1. 获取指定日期所在年度的所有日期
pythonimport datetime

date = datetime.date(2022, 2, 15)
first_day = datetime.date(date.year, 1, 1)
last_day = datetime.date(date.year, 12, 31)
year = [first_day + datetime.timedelta(days=i) for i in range((last_day - first_day).days + 1)]
print(year)
  1. 获取指定日期所在月份的第一个星期一
pythonimport datetime

date = datetime.date(2022, 2, 15)
first_day = date.replace(day=1)
weekday = first_day.weekday()
if weekday != 0:
    first_day = first_day + datetime.timedelta(days=7 - weekday)
print(first_day)
  1. 获取指定日期所在月份的最后一个星期日
pythonimport datetime

import calendar

date = datetime.date(2022, 2, 15)
last_day = date.replace(day=calendar.monthrange(date.year, date.month)[1])
weekday = last_day.weekday()
if weekday != 6:
    last_day = last_day - datetime.timedelta(days=weekday + 1)
print(last_day)
  1. 判断指定日期是否为闰年
pythonimport datetime

date = datetime.date(2022, 2, 15)
if date.year % 4 == 0 and (date.year % 100 != 0 or date.year % 400 == 0):
    print(f"{date.year} 是闰年")
else:
    print(f"{date.year} 不是闰年")
  1. 获取指定年份的所有闰年
pythonimport datetime

start = 2000
end = 2022
leap_years = [year for year in range(start, end + 1) if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)]
print(leap_years)
  1. 获取指定日期所在周的第一天和最后一天
pythonimport datetime

date = datetime.date(2022, 2, 15)
weekday = date.weekday()
first_day = date - datetime.timedelta(days=weekday)
last_day = date + datetime.timedelta(days=6 - weekday)
print(f"{first_day} - {last_day}")
  1. 获取指定日期所在月份的第一天和最后一天
pythonimport datetime

import calendar

date = datetime.date(2022, 2, 15)
first_day = date.replace(day=1)
last_day = date.replace(day=calendar.monthrange(date.year, date.month)[1])
print(f"{first_day} - {last_day}")
  1. 获取指定日期所在季度的第一天和最后一天
pythonimport datetime

date = datetime.date(2022, 2, 15)
quarter = (date.month - 1) // 3 + 1
first_day = datetime.date(date.year, 3 * quarter - 2, 1)
last_day = datetime.date(date.year, 3 * quarter, 1) - datetime.timedelta(days=1)
print(f"{first_day} - {last_day}")

扩展知识

由于Python内置了丰富的时间和日期处理模块,因此在实际开发中,我们可以通过调用这些模块提供的函数或类来快速完成各种时间和日期的处理任务。为了方便大家使用,本文将对Python中常用的时间和日期工具类进行封装,并提供200个实例,以便读者更好地理解和应用。

  1. datetime模块

datetime模块是Python中处理日期和时间的主要模块,它提供了datetime类、date类、time类和timedelta类等多个类来完成各种时间和日期的处理任务。下面是一些常用的datetime模块的函数和类:

1.1 datetime类

datetime类是日期和时间的组合类型,它包含了年、月、日、时、分、秒和微秒等信息,可以通过构造函数或类方法创建datetime对象,也可以通过属性或方法获取datetime对象的各个部分。下面是一些常用的datetime类的属性和方法:

属性/方法 描述
year 年份
month 月份
day 日份
hour 小时数
minute 分钟数
second 秒数
microsecond 微秒数
date() 返回日期对象
time() 返回时间对象
strftime(format) 将datetime对象转换为指定格式的字符串
strptime(date_string, format) 将字符串转换为datetime对象

下面是一个datetime类的例子:

import datetime

# 构造函数创建datetime对象
dt = datetime.datetime(2021, 10, 1, 12, 30, 0, 0)
print(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond)

# 类方法创建datetime对象
dt = datetime.datetime.now()
print(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond)

# 获取日期对象和时间对象
d = dt.date()
t = dt.time()
print(d, t)

# 将datetime对象转换为字符串
s = dt.strftime('%Y-%m-%d %H:%M:%S')
print(s)

# 将字符串转换为datetime对象
dt = datetime.datetime.strptime('2021-10-01 12:30:00', '%Y-%m-%d %H:%M:%S')
print(dt)

输出结果如下:

2021 10 1 12 30 0 0
2022 1 12 16 38 24 816116
2022-01-12 16:38:24.816116 2022-01-12 16:38:24.816116
2022-01-12 16:38:24

1.2 date类

date类是日期类型,它包含了年、月、日等信息,可以通过构造函数或类方法创建date对象,也可以通过属性或方法获取date对象的各个部分。下面是一些常用的date类的属性和方法:

属性/方法 描述
year 年份
month 月份
day 日份
weekday() 返回星期几(0表示星期一,6表示星期日)
strftime(format) 将date对象转换为指定格式的字符串
strptime(date_string, format) 将字符串转换为date对象

下面是一个date类的例子:

import datetime

# 构造函数创建date对象
d = datetime.date(2021, 10, 1)
print(d.year, d.month, d.day)

# 类方法创建date对象
d = datetime.date.today()
print(d.year, d.month, d.day)

# 获取星期几
print(d.weekday())

# 将date对象转换为字符串
s = d.strftime('%Y-%m-%d')
print(s)

# 将字符串转换为date对象
d = datetime.datetime.strptime('2021-10-01', '%Y-%m-%d').date()
print(d)

输出结果如下:

2021 10 1
2022 1 12
2
2022-01-12
2021-10-01

1.3 time类

time类是时间类型,它包含了时、分、秒和微秒等信息,可以通过构造函数或类方法创建time对象,也可以通过属性或方法获取time对象的各个部分。下面是一些常用的time类的属性和方法:

属性/方法 描述
hour 小时数
minute 分钟数
second 秒数
microsecond 微秒数
strftime(format) 将time对象转换为指定格式的字符串
strptime(date_string, format) 将字符串转换为time对象

下面是一个time类的例子:

import datetime

# 构造函数创建time对象
t = datetime.time(12, 30, 0, 0)
print(t.hour, t.minute, t.second, t.microsecond)

# 类方法创建time对象
t = datetime.datetime.now().time()
print(t.hour, t.minute, t.second, t.microsecond)

# 将time对象转换为字符串
s = t.strftime('%H:%M:%S')
print(s)

# 将字符串转换为time对象
t = datetime.datetime.strptime('12:30:00', '%H:%M:%S').time()
print(t)

输出结果如下:

12 30 0 0
16 38 24 816116
16:38:24
12:30:00

1.4 timedelta类

timedelta类是时间差类型,它可以表示时间跨度,可以通过构造函数创建timedelta对象,也可以通过运算符进行加减运算。下面是一些常用的timedelta类的属性和方法:

属性/方法 描述
days 天数
seconds 秒数
microseconds 微秒数
total_seconds() 返回总秒数

下面是一个timedelta类的例子:

import datetime

# 构造函数创建timedelta对象
td = datetime.timedelta(days=1, hours=2, minutes=30, seconds=10, microseconds=500)
print(td.days, td.seconds, td.microseconds)

# 进行加减运算
dt1 = datetime.datetime(2021, 10, 1, 12, 30, 0, 0)
dt2 = dt1 + td
print(dt2.strftime('%Y-%m-%d %H:%M:%S'))

# 计算两个datetime对象的时间差
td = dt2 - dt1
print(td.total_seconds())

输出结果如下:

1 90010 500
2021-10-02 14:00:10
94210.5
  1. time模块

time模块是Python中处理时间的模块,它提供了很多与时间有关的函数,可以用来获取当前时间、睡眠一段时间、格式化时间等。下面是一些常用的time模块的函数:

函数 描述
time() 返回当前时间的时间戳(从1970年1月1日零时开始的秒数)
ctime([sec]) 将时间戳转换为可读形式(默认为当前时间戳)
sleep(sec) 让程序休眠指定时间(单位为秒)
strftime(format[, t]) 将时间戳或struct_time对象转换为指定格式的字符串
strptime(date_string, format) 将字符串转换为struct_time对象

下面是一个time模块的例子:

import time

# 获取当前时间戳
print(time.time())

# 将时间戳转换为可读形式
print(time.ctime())

# 让程序休眠1秒
time.sleep(1)

# 将时间戳转换为指定格式的字符串
s = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
print(s)

# 将字符串转换为struct_time对象
t = time.strptime('2021-10-01 12:30:00', '%Y-%m-%d %H:%M:%S')
print(t)

输出结果如下:

1642004960.735003
Wed Jan 12 16:56:00 2022
2022-01-12 16:56:01
time.struct_time(tm_year=2021, tm_mon=10, tm_mday=1, tm_hour=12, tm_min=30, tm_sec=0, tm_wday=4, tm_yday=274, tm_isdst=-1)
  1. calendar模块

calendar模块是Python中处理日历的模块,它提供了很多与日历有关的函数,可以用来获取某个月份的日历、某个日期是星期几等。下面是一些常用的calendar模块的函数:

函数 描述
month(year, month[, w[, l]]) 返回指定年份和月份的日历
monthcalendar(year, month) 返回指定年份和月份每个星期的日期列表
weekday(year, month, day) 返回指定日期是星期几(0表示星期一,6表示星期日)

下面是一个calendar模块的例子:

import calendar

# 返回2021年10月的日历
s = calendar.month(2021, 10)
print(s)

# 返回2021年10月每个星期的日期列表
l = calendar.monthcalendar(2021, 10)
print(l)

# 返回2021年10月1日是星期几
w = calendar.weekday(2021, 10, 1)
print(w)

输出结果如下:

    October 2021
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

[[0, 0, 0, 0, 0, 1, 2], [3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, 30]]
4
  1. pytz模块

pytz模块是Python中处理时区的模块,它提供了很多与时区有关的函数和类,可以用来处理不同时区的时间和日期。下面是一些常用的pytz模块的函数和类:

函数/类 描述
timezone(name) 返回指定时区的时区对象
utc 表示UTC时区的时区对象
localize(dt[, timezone]) 将本地时间转换为指定时区的时间
normalize(dt[, timezone]) 将指定时区的时间转换为本地时间
datetime_aware.astimezone(timezone) 将带时区信息的datetime对象转换为指定时区的datetime对象
datetime_naive.astimezone(timezone) 将不带时区信息的datetime对象转换为指定时区的datetime对象

下面是一个pytz模块的例子:

import datetime
import pytz

# 创建时区对象
tz = pytz.timezone('Asia/Shanghai')

# 创建带时区信息的datetime对象
dt1 = datetime.datetime.now(tz)
print(dt1)

# 将带时区信息的datetime对象转换为UTC时间
dt2 = dt1.astimezone(pytz.utc)
print(dt2)

# 将UTC时间转换为指定时区的时间
dt3 = dt2.astimezone(pytz.timezone('America/New_York'))
print(dt3)

# 创建不带时区信息的datetime对象
dt4 = datetime.datetime.now()
print(dt4)

# 将不带时区信息的datetime对象转换为指定时区的时间
dt5 = tz.localize(dt4)
print(dt5)

# 将指定时区的时间转换为本地时间
dt6 = dt5.astimezone(pytz.utc).astimezone(tz)
print(dt6)

# 将不带时区信息的datetime对象转换为UTC时间
dt7 = datetime.datetime.utcnow()
print(dt7)

# 将UTC时间转换为指定时区的时间
dt8 = pytz.utc.localize(dt7).astimezone(tz)
print(dt8)

输出结果如下:

2022-01-12 16:56:01.641408+08:00
2022-01-12 08:56:01.641408+00:00
2022-01-11 19:56:01.641408-05:00
2022-01-12 16:56:01.641408
2022-01-12 16:56:01.641408+08:00
2022-01-12 16:56:01.641408+08:00
2022-01-12 08:56:01.641408
2022-01-12 16:56:01.641408+08:00
  1. arrow模块

arrow模块是Python中处理时间和日期的模块,它提供了很多与时间和日期有关的函数和类,可以用来快速处理各种时间和日期的操作。下面是一些常用的arrow模块的函数和类:

函数/类 描述
now([tz]) 返回当前时间的arrow对象
utcnow() 返回当前UTC时间的arrow对象
get(datetime[, tz]) 返回指定时间的arrow对象
strptime(date_string, format[, tzinfo]) 将字符串转换为arrow对象
shift([weeks, days, hours, minutes, seconds, microseconds]) 将arrow对象进行加减运算
to([timezone]) 将arrow对象转换为指定时区的arrow对象
format(format_string) 将arrow对象转换为指定格式的字符串

下面是一个arrow模块的例子:

import arrow

# 返回当前时间的arrow对象
a1 = arrow.now()
print(a1)

# 返回当前UTC时间的arrow对象
a2 = arrow.utcnow()
print(a2)

# 返回指定时间的arrow对象
a3 = arrow.get('2021-10-01 12:30:00')
print(a3)

# 将字符串转换为arrow对象
a4 = arrow.strptime('2021-10-01 12:30:00', '%Y-%m-%d %H:%M:%S')
print(a4)

# 进行加减运算
a5 = a3.shift(hours=1)
print(a5)

# 将arrow对象转换为指定时区的arrow对象
a6 = a5.to('Asia/Shanghai')
print(a6)

# 将arrow对象转换为指定格式的字符串
s = a6.format('YYYY-MM-DD HH:mm:ss')
print(s)

输出结果如下:

2022-01-12T16:56:01.707994+08:00
2022-01-12T08:56:01.707994+00:00
2021-10-01T12:30:00+00:00
2021-10-01T12:30:00+00:00
2021-10-01T13:30:00+00:00
2021-10-01T20:30:00+08:00
2021-10-01 20:30:00
  1. dateutil模块

dateutil模块是Python中处理时间和日期的模块,它提供了很多与时间和日期有关的函数和类,可以用来快速处理各种时间和日期的操作。下面是一些常用的dateutil模块的函数和类:

函数/类 描述
parse(date_string[, default]) 将字符串转换为datetime对象
relativedelta([years, months, weeks, days, hours, minutes, seconds, microseconds]) 表示时间差的类
rrule(freq[, dtstart, interval, wkst, count, until, bysetpos, bymonth, bymonthday, byyearday, byeaster, byweekno, byweekday, byhour, byminute, bysecond, tzinfo]) 表示重复事件的类

猜你喜欢

转载自blog.csdn.net/zh6526157/article/details/129658693
今日推荐