목차
1. 날짜 및 시간 객체
2. 날짜 및 시간 객체 생성
2.1. datetime.datetime.utcnow()를 통해 생성
2.2 datetime.datetime.today() 함수를 통해 생성
2.3. )
2.4.datetime.datetime()으로 생성
내에 있어야 합니다. 2.5 생성된 개체 보기
2.6. 그리고 datetime이 처리할 수 있는 시간 객체
3. Date 이벤트 객체
4. 날짜 및 시간 개체는 시간 튜플로 변환됩니다.
5. 날짜 및 시간 개체를 AD 달력에서 시작하는 일 수로 변환
예: Sat Jul 9 19:14:27 2022(2022년 7월 9일 일요일)
백엔드 개발 파이썬 튜토리얼 Python에서 datetime 모듈을 사용하는 방법

Python에서 datetime 모듈을 사용하는 방법

May 30, 2023 am 09:52 AM
python datetime

    1. 날짜 및 시간 객체

    • 날짜 및 시간 객체는 날짜(년, 월, 일)와 시간(시, 분, 초)의 이중 속성을 갖는 인스턴스를 나타냅니다. 날짜 및 시간 객체의 유형은 datetime.datetime입니다

    • 날짜 및 시간 객체의 일반적으로 사용되는 속성은 연, 월, 일, 시, 분, 초 및 마이크로초입니다.

    • 날짜 및 시간 객체는 한 번에 생성할 수 있습니다. 지정된 시간 또는 현재 시간을 가져와

    • 날짜 및 시간 지정된 시간에 객체가 생성될 때 위치별로 매개변수를 전달하거나 키워드로 매개변수를 전달하여 생성할 수 있습니다. include datetime.datetime(), datetime.datetime.now(), datetime.datetime.today( ), datetime.datetime.utcnow()

    • datetime.datetime()을 통해 datetime 객체가 생성될 때의 매개변수는 다음과 같습니다. year,month,day,hour,min,second,microsecond

    • datetime 객체가 전달됩니다. datetime.datetime.now() 함수는 매개변수를 생성하지 않습니다.

    • Datetime 객체는 datetime.datetime.today에 의해 생성됩니다. () 함수입니다.

    • Datetime 객체는 datetime.datetime.utcnow() 함수에 의해 생성됩니다. 필수 매개변수

    • datetime.datetime()을 통해 날짜 및 시간 객체가 생성됩니다. 연, 월, 일 세 개 이상의 매개변수가 포함되어야 합니다

    • datetime.datetime()을 통해 날짜 및 시간 객체가 생성될 때 매개변수 범위는 다음과 같습니다

    • 일련번호

      형식 매개변수
    실제 매개변수 범위
    1 1~9999
    2 1~12
    3 0~23
    4 0~23
    5 0~59
    6 0~59
    7 마이크로초 1~999999

    2. 날짜 및 시간 객체 생성

    2.1. datetime.datetime.utcnow()를 통해 생성

    datetime_zero = datetime.datetime.utcnow()
    로그인 후 복사

    2.2 datetime.datetime.today() 함수를 통해 생성

    datetime_first = datetime.datetime.today()
    로그인 후 복사

    2.3. )

    datetime_second = datetime.datetime.now()
    로그인 후 복사

    2.4.datetime.datetime()으로 생성

    • 생성할 날짜와 시간을 지정하세요.

    • 연도, 월, 일 매개변수를 전달해야 합니다.

    • 날짜와 시간, 순서를 지정하세요. 위치 매개변수는 변경할 수 없으며 매개변수 값은 지정된 범위

    datetime_three = datetime.datetime(year=1, month=1, day=1, hour=0, minute=0, second=0, microsecond=1)
    datetime_four = datetime.datetime(year=9999, month=12, day=31, hour=23, minute=59, second=59, microsecond=999999)
    datetime_five = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
    로그인 후 복사

    내에 있어야 합니다. 2.5 생성된 개체 보기

    print(datetime_zero, type(datetime_zero))       # 2022-07-09 18:12:43.486469 <class &#39;datetime.datetime&#39;>
    print(datetime_first, type(datetime_first))     # 2022-07-09 18:12:43.486469 <class &#39;datetime.datetime&#39;>
    print(datetime_second, type(datetime_second))   # 2022-07-09 18:12:43.486469 <class &#39;datetime.datetime&#39;>
    print(datetime_three, type(datetime_three))     # 0001-01-01 00:00:00.000001 <class &#39;datetime.datetime&#39;>
    print(datetime_four, type(datetime_four))       # 9999-12-31 23:59:59.999999 <class &#39;datetime.datetime&#39;>
    print(datetime_five, type(datetime_five))       # 9999-12-31 23:59:59.999999 <class &#39;datetime.datetime&#39;>
    로그인 후 복사

    Python에서 datetime 모듈을 사용하는 방법

    2.6. 그리고 datetime이 처리할 수 있는 시간 객체

    print(datetime.datetime.min)        # 0001-01-01 00:00:00
    print(datetime.datetime.max)        # 9999-12-31 23:59:59.999999
    로그인 후 복사

    Python에서 datetime 모듈을 사용하는 방법

    3. Date 이벤트 객체

    datetime_first = datetime.datetime.today()
    """# 从日期时间对象中获取日期属性【年-月-日】"""
    new_time = datetime.datetime.date(datetime_first)
    print(new_time)
    print(type(new_time))
    """# 从日期时间对象中获取时间属性【时:分:秒:微秒】"""
    new_time = datetime.datetime.time(datetime_first)
    print(new_time)
    print(type(new_time))
    """# 从日期时间对象中获取年份"""
    datetime_year = datetime_first.year
    print(datetime_year, type(datetime_year))       # 2022 <class &#39;int&#39;>
    """# 从日期时间对象中获取月份"""
    datetime_month = datetime_first.month
    print(datetime_month, type(datetime_month))       # 7 <class &#39;int&#39;>
    """# 从日期时间对象中获取天"""
    datetime_day = datetime_first.day
    print(datetime_day, type(datetime_day))       # 10 <class &#39;int&#39;>
    """# 从日期时间对象中获取小时"""
    datetime_hour = datetime_first.hour
    print(datetime_hour, type(datetime_hour))       # 18 <class &#39;int&#39;>
    """# 从日期时间对象中获取分钟"""
    datetime_minute = datetime_first.minute
    print(datetime_minute, type(datetime_minute))       # 56 <class &#39;int&#39;>
    """# 从日期时间对象中获取秒数"""
    datetime_second = datetime_first.second
    print(datetime_second, type(datetime_second))       # 16 <class &#39;int&#39;>
    """# 从日期时间对象中获取微秒"""
    datetime_microsecond = datetime_first.microsecond
    print(datetime_microsecond, type(datetime_microsecond))       # 735264 <class &#39;int&#39;>
    로그인 후 복사

    의 속성"""# datetime.datetime.date() 함수의 매개변수는 datetime.datetime 유형이어야 합니다."""
    date_time = datetime.date(2022, 12, 26)

    """# Pass 입력한 매개변수는 datetime.date 유형이 될 수 없습니다. """
    """# TypeError: ‘datetime에 대한 설명자 ‘date’ datetime' 객체는 'datetime.date' 객체에 적용되지 않습니다."""
    " ""# print(datetime.datetime.date(date_time))"""

    time_time = datetime.time(12, 2, 54, 999999)
    """# 전달된 매개변수는 datetime.time 유형일 수 없습니다."" "
    """# TypeError: ‘datetime.datetime’ 개체에 대한 설명자 ‘date’는 ‘에 적용되지 않습니다. ;datetime.time’ object"""
    """# print(datetime.datetime.date( time_time))"""
    """# 마찬가지로 datetime.datetime.time() 함수에 의해 전달된 매개변수는 datetime.date 유형 및 datetime.time 유형이어야 합니다."""
    """# TypeError: ‘datetime.datetime’ 개체에 대한 설명자 ’datetime.date’ 개체에 적용되지 않습니다."""
    """# print(datetime.datetime.time(date_time))"""
    """ # TypeError: ‘datetime.datetime’ 개체에 대한 설명자 ‘시간’이 ‘datetime.time’에 적용되지 않습니다. object"""
    """# print(datetime.datetime.time(time_time))"" "

    Python에서 datetime 모듈을 사용하는 방법

    4. 날짜 및 시간 개체는 시간 튜플로 변환됩니다.

    • 시간 튜플은 연도, 월, 일, 시, 분, 초, N번째 요일 및 연도가 포함된 시간 튜플 N번째 날 및 일광 절약 시간 표시

    • 시간 튜플 예: (tm_year=2022, tm_mon= 7, tm_mday=9, tm_hour=19, tm_min=14, tm_sec=27, tm_wday=5, tm_yday=190, tm_isdst=0)

    • tm_wday의 값은 0부터 시작하고 범위는 0~6입니다. 0은 월요일, 6은 일요일입니다. tm_isdst=0은 일광 절약 시간이 활성화되지 않았음을 의미합니다

    UTCDateTime = datetime.datetime(year=2022, month=7, day=10, hour=19, minute=14, second=27, microsecond=1235)
    datetime_UTCTimeTuple = datetime.datetime.utctimetuple(UTCDateTime)
    print(datetime_UTCTimeTuple, type(datetime_UTCTimeTuple))  # 类型为:<class &#39;time.struct_time&#39;>
    로그인 후 복사

    Python에서 datetime 모듈을 사용하는 방법

    5. 날짜 및 시간 개체를 AD 달력에서 시작하는 일 수로 변환

    • 정수 값을 날짜 및 시간 개체로 변환

    • 정수 값 최대값은 3652059

    • datetime_replace = datetime.datetime(year=2022, month=7, day=9, hour=19, minute=14, second=27, microsecond=123)
      datetime_ordinal = datetime.datetime.toordinal(datetime_replace)
      print(datetime_ordinal, type(datetime_ordinal))     # 738345 <class &#39;int&#39;>
      print(datetime.datetime.fromordinal(1))     # 0001-01-02 00:00:00
      print(datetime.datetime.fromordinal(2))     # 0001-01-02 00:00:00
      datetime_replace_max = datetime.datetime(year=9999, month=12, day=31, hour=23, minute=59, second=59, microsecond=999999)
      print(datetime.datetime.toordinal(datetime_replace_max))
      print(datetime.datetime.fromordinal(3652060))
      로그인 후 복사

    Python에서 datetime 모듈을 사용하는 방법

    6. 날짜 및 시간 객체는 날짜 형식 값의 문자열로 변환됩니다

    Python에서 datetime 모듈을 사용하는 방법

    예: Sat Jul 9 19:14:27 2022(2022년 7월 9일 일요일)

    • 첫 번째 부분의 값은 day of the week

    • 두 번째 부분의 값은 월을 나타냅니다

    • 세 번째 부분의 값은 일을 나타냅니다.

    • 네 번째 부분의 값은 시간을 나타냅니다

    • 값 다섯 번째 부분은 연도를 나타냅니다

    • datetime_replace = datetime.datetime(year=2022, month=7, day=9, hour=19, minute=14, second=27, microsecond=123)
      print(datetime_replace)
      ctime_datetime = datetime.datetime.ctime(datetime_replace)
      print(ctime_datetime, type(ctime_datetime))
      ```
      ![Python标准库datetime之datetime模块详解_date_07](https://img-blog.csdnimg.cn/b7e257debb0249ca84463b9d73d7dbf1.png)
      ## 7、日期时间对象转换为时间戳
      ```python
      datetime_timestamp = datetime.datetime.timestamp(datetime_replace)
      print(datetime_timestamp, type(datetime_timestamp))         # 1657365267.000123 
      ```
      ![Python标准库datetime之datetime模块详解_datetime_08](https://img-blog.csdnimg.cn/e38e2a5be32242c5a79441e7300e2fc2.png)
      ## 8、时间戳转换为日期时间对象
      ```python
      print(datetime.datetime.fromtimestamp(datetime_timestamp))  # 2022-07-09 19:14:27.000123
      ```
      ![Python标准库datetime之datetime模块详解_datetime_08](https://img-blog.csdnimg.cn/e38e2a5be32242c5a79441e7300e2fc2.png)
      ## 9、日期时间对象转换为时间元组
      ```python
      datetime_timetuple = datetime.datetime.timetuple(datetime_replace)
      print(datetime_timetuple, type(datetime_timetuple))
      ```
      ![Python标准库datetime之datetime模块详解_datetime_08](https://img-blog.csdnimg.cn/e38e2a5be32242c5a79441e7300e2fc2.png)
      ## 10、ISO标准日期时间格式
      ISO标准的日历时间,Calendar中文释义为日历
      * 各个值的含义为(年份、周数、周内的第N天)即(year, week, weekday);
      * weekday的值为[1,7],1代表周一,7代表周日
      * 示例:datetime.IsoCalendarDate(year=2022, week=27, weekday=7)
      ```python
      datetime_replace = datetime.datetime(year=2022, month=7, day=9, hour=19, minute=14, second=27, microsecond=123)
      UTCDateTime = datetime.datetime(year=2022, month=7, day=10, hour=19, minute=14, second=27, microsecond=1235)
      # ISO标准日期时间格式
      print(datetime.datetime.utcoffset(UTCDateTime))
      # 将日期时间对象转换为ISO标准日期时间格式的字符串
      UTC_ISO_DateTime = datetime.datetime.isoformat(UTCDateTime)
      print(UTC_ISO_DateTime, type(UTC_ISO_DateTime))         # 2022-07-10T19:14:27.001235 
      # 将ISO标准日期时间格式的字符串转换为日期时间类型
      From_UTC_ISO_DateTime = datetime.datetime.fromisoformat('9999-12-31T23:59:59.999999')   # 
      print(From_UTC_ISO_DateTime, type(From_UTC_ISO_DateTime))
      # ISO标准的周内第N天
      # 值的范围是[1,7],1代表周一,7代表周日
      UTC_ISO_WeekDateTime = datetime.datetime.isoweekday(UTCDateTime)
      print(UTC_ISO_WeekDateTime, type(UTC_ISO_WeekDateTime))     # 7 
      # ISO标准的日历时间,Calendar中文释义为日历
      # 各个值的含义为(年份、周数、周内的第N天)即(year, week, weekday);
      # weekday的值为[1,7],1代表周一,7代表周日
      # 示例:datetime.IsoCalendarDate(year=2022, week=27, weekday=7)
      UTC_ISO_CalendarDateTime = datetime.datetime.isocalendar(UTCDateTime)
      print(UTC_ISO_CalendarDateTime, type(UTC_ISO_CalendarDateTime))
      # 将ISO标准日历格式的字符串转换为时间日期型
      From_UTC_ISO_CalendarDateTime = datetime.datetime.fromisocalendar(year=2022, week=27, day=7)
      print(From_UTC_ISO_CalendarDateTime)        # 2022-07-10 00:00:00
      print(type(From_UTC_ISO_CalendarDateTime))  # 
      ```
      ![Python标准库datetime之datetime模块详解_python_11](https://img-blog.csdnimg.cn/bb944815182d477a9a662862f13a9f3a.png)
      ## 11、日期时间替换函数replace()
      *  replace()可以只替换日期时间属性的某一项
      * replace()函数的第一个参数必传
      * replace()函数的第一个参数是一个日期时间类型(datetime.datetime)的对象
      * 按关键字传参替换
      * 按位置传参体换
      ```python
      datetime_replace = datetime.datetime(year=2022, month=7, day=9, hour=19, minute=14, second=27, microsecond=123)
      # 初始值
      print(f"datetime_replace的原值为:{datetime_replace}", f"类型是:{type(datetime_replace)}")
      # 不传参数
      print(datetime.datetime.replace(datetime_replace))    # 2022-07-09 19:14:27.000123
      # 只替换年份
      print(datetime.datetime.replace(datetime_replace, 2019))    # 2019-07-09 19:14:27.000123
      print(datetime.datetime.replace(datetime_replace, year=2019))   # 2019-07-09 19:14:27.000123
      # 只替换月份, 替换其他参数同理
      print(datetime.datetime.replace(datetime_replace, month=12))            # 2022-12-09 19:14:27.000123
      print(datetime.datetime.replace(datetime_replace, datetime_replace.year, 12))   # 2022-12-09 19:14:27.000123
      # 替换其他参数同理
      print(datetime.datetime.replace(datetime_replace, year=2019, month=12, day=31, hour=15,
                                      minute=13, second=15, microsecond=9999))    # 2019-12-31 15:13:15.009999
      ```
      ![Python标准库datetime之datetime模块详解_date_12](https://img-blog.csdnimg.cn/4ed28241d33b4928b3a8b2132b08a7d6.png)
      ## 12、日期时间对象格式化strftime()
      * 日期时间对象格式化常用的格式如下
      * %H(两位数的小时)
      * %M(两位数的分钟)
      * %S(两位数的秒)
      * %f(6位数的微秒)
      * %h(简写的月份名,一般为英文简写)
      * %y(两位数的年份)
      * %Y(四位数的年份)
      * %m(两位数的月份)
      * %d(两位数的天数)
      * 可以只格式化部分属性
      ```python
      datetime_replace = datetime.datetime(year=2022, month=7, day=9, hour=19, minute=14, second=27, microsecond=123)
      # 可以只格式化部分属性
      datetime_str = datetime.datetime.strftime(datetime_replace, "%Y-%m-%d %H:%M:%S.%f")
      print(f"格式化后是:{datetime_str}", type(datetime_str))      # 2022-07-09 19:14:27.000123 
      # 格式化日期属性
      datetime_str_date = datetime.datetime.strftime(datetime_replace, "%Y-%m-%d")
      print(f"格式化日期的值为:{datetime_str_date}")      # 2022-07-09
      # 格式时间属性
      datetime_str_time = datetime.datetime.strftime(datetime_replace, "%H:%M:%S.%f")
      print(f"格式化时间的值为:{datetime_str_time}")      # 19:14:27.000123
      ```
      ![Python标准库datetime之datetime模块详解_datetime_13](https://img-blog.csdnimg.cn/4d9da4de3f464f1ca73e30f918406a0a.png)
      ## 附录、完整代码
      ```python
      # coding:utf-8
      import datetime
      # 日期时间对象
      # 日期时间对象是指具有日期(年月日)和时间(时分秒)双重属性的实例
      # 日期时间对象的类型为datetime.datetime
      # 日期时间对象常用的属性有年、月、日、时、分、秒、微秒等
      # 日期时间对象可以指定时间创建,也可以通过获取当前时间来创建
      # 日期时间对象指定时间创建时可按位置传参创建,也可关键字传参创建
      # 日期时间对象的创建函数有datetime.datetime(),datetime.datetime.now()、datetime.datetime.today()、datetime.datetime.utcnow()
      # 日期时间对象通过datetime.datetime()创建时的参数依次为:year,month,day,hour,minute,second,microsecond
      # 日期时间对象通过datetime.datetime.now()函数创建不需要参数
      # 日期时间对象通过datetime.datetime.today()函数创建不需要参数
      # 日期时间对象通过datetime.datetime.utcnow()函数创建不需要参数
      # 日期时间对象通过datetime.datetime()创建时至少应该包含年月日三个参数
      # 日期时间对象通过datetime.datetime()创建时的参数范围如下
      # {year[1~9999]、month[1~12]、day[1~31]、hour[0~23]、minute[0~59]、second[0~59]、microsecond[1~999999]}
      
      # 通过datetime.datetime.utcnow()创建
      datetime_zero = datetime.datetime.utcnow()
      # 通过datetime.datetime.today()函数创建
      datetime_first = datetime.datetime.today()
      # 通过datetime.datetime.now()创建
      datetime_second = datetime.datetime.now()
      # 通过datetime.datetime()函数指定日期时间、关键字传参创建
      datetime_three = datetime.datetime(year=1, month=1, day=1, hour=0, minute=0, second=0, microsecond=1)
      datetime_four = datetime.datetime(year=9999, month=12, day=31, hour=23, minute=59, second=59, microsecond=999999)
      # 通过datetime.datetime()函数指定日期时间、按位置传参创建,顺序不可变且参数值必须在规定的范围内
      datetime_five = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
      print(datetime_zero, type(datetime_zero))       # 2022-07-09 18:12:43.486469 <class &#39;datetime.datetime&#39;>
      print(datetime_first, type(datetime_first))     # 2022-07-09 18:12:43.486469 <class &#39;datetime.datetime&#39;>
      print(datetime_second, type(datetime_second))   # 2022-07-09 18:12:43.486469 <class &#39;datetime.datetime&#39;>
      print(datetime_three, type(datetime_three))     # 0001-01-01 00:00:00.000001 <class &#39;datetime.datetime&#39;>
      print(datetime_four, type(datetime_four))       # 9999-12-31 23:59:59.999999 <class &#39;datetime.datetime&#39;>
      print(datetime_five, type(datetime_five))       # 9999-12-31 23:59:59.999999 <class &#39;datetime.datetime&#39;>
      # 查看datetime可以处理的最大的日期时间对象及最小的日期时间对象
      print(datetime.datetime.min)        # 0001-01-01 00:00:00
      print(datetime.datetime.max)        # 9999-12-31 23:59:59.999999
      
      """# 从日期时间对象中获取日期属性【年-月-日】"""
      new_time = datetime.datetime.date(datetime_first)
      print(new_time)
      print(type(new_time))
      """# 从日期时间对象中获取时间属性【时:分:秒:微秒】"""
      new_time = datetime.datetime.time(datetime_first)
      print(new_time)
      print(type(new_time))
      """# 从日期时间对象中获取年份"""
      datetime_year = datetime_four.year
      print(datetime_year, type(datetime_year))       # 9999 
      """# 从日期时间对象中获取月份"""
      datetime_month = datetime_four.month
      print(datetime_month, type(datetime_month))       # 12 
      """# 从日期时间对象中获取天"""
      datetime_day = datetime_four.day
      print(datetime_day, type(datetime_day))       # 31 
      """# 从日期时间对象中获取小时"""
      datetime_hour = datetime_four.hour
      print(datetime_hour, type(datetime_hour))       # 23 
      """# 从日期时间对象中获取分钟"""
      datetime_minute = datetime_four.minute
      print(datetime_minute, type(datetime_minute))       # 59 
      """# 从日期时间对象中获取秒数"""
      datetime_second = datetime_four.second
      print(datetime_second, type(datetime_second))       # 59 
      """# 从日期时间对象中获取微秒"""
      datetime_microsecond = datetime_four.microsecond
      print(datetime_microsecond, type(datetime_microsecond))       # 999999 
      """# datetime.datetime.date()函数的参数只能是datetime.datetime类型"""
      date_time = datetime.date(2022, 12, 26)
      """# 传入的参数不能为datetime.date类型"""
      """# TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'datetime.date' object"""
      """# print(datetime.datetime.date(date_time))"""
      time_time = datetime.time(12, 2, 54, 999999)
      """# 传入的参数不能为datetime.time类型"""
      """# TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'datetime.time' object"""
      """# print(datetime.datetime.date(time_time))"""
      """# 同理,datetime.datetime.time()函数传入的参数亦不能为datetime.date类型和datetime.time类型"""
      """# TypeError: descriptor 'time' for 'datetime.datetime' objects doesn't apply to a 'datetime.date' object"""
      """# print(datetime.datetime.time(date_time))"""
      """# TypeError: descriptor 'time' for 'datetime.datetime' objects doesn't apply to a 'datetime.time' object"""
      """# print(datetime.datetime.time(time_time))"""
      # 将日期时间对象转换为时间元组类型
      # 时间元组是指具有 年份、月份、日、小时、分钟、秒数、星期中的第N天、年中的第N天、夏令时标志的一个元组对象
      # 时间元组示例:(tm_year=2022, tm_mon=7, tm_mday=9, tm_hour=19, tm_min=14, tm_sec=27, tm_wday=5, tm_yday=190, tm_isdst=0)
      # 其中tm_wday的值从0开始,范围是:0~6,0为星期一,6为星期日;tm_isdst=0代表未启用夏令时
      UTCDateTime = datetime.datetime(year=2022, month=7, day=10, hour=19, minute=14, second=27, microsecond=1235)
      datetime_UTCTimeTuple = datetime.datetime.utctimetuple(UTCDateTime)
      print(datetime_UTCTimeTuple, type(datetime_UTCTimeTuple))  # 类型为:<class &#39;time.struct_time&#39;>
      # 将日期时间对象转化为公元历开始计数的天数
      datetime_replace = datetime.datetime(year=2022, month=7, day=9, hour=19, minute=14, second=27, microsecond=123)
      datetime_ordinal = datetime.datetime.toordinal(datetime_replace)
      print(datetime_ordinal, type(datetime_ordinal))     # 738345 
      print(datetime.datetime.fromordinal(1))     # 0001-01-02 00:00:00
      print(datetime.datetime.fromordinal(2))     # 0001-01-02 00:00:00
      # ctime()是将日期时间类型转换为一个日期之间值的字符串,示例如 Sat Jul  9 19:14:27 2022(2022年7月9日星期六)
      # ctime()返回值的第一部分的值代表星期几,第二部分的值代表月份,第三部分的值代表日,第四部分的值代表时间,第五部分的值代表年份
      print(datetime_replace)
      ctime_datetime = datetime.datetime.ctime(datetime_replace)
      print(ctime_datetime, type(ctime_datetime))
      
      # 将日期时间对象转换为时间戳
      datetime_timestamp = datetime.datetime.timestamp(datetime_replace)
      print(datetime_timestamp, type(datetime_timestamp))         # 1657365267.000123 
      # 将时间戳转换为日期时间对象
      print(datetime.datetime.fromtimestamp(datetime_timestamp))  # 2022-07-09 19:14:27.000123
      
      # 将日期时间对象转换为时间元组
      datetime_timetuple = datetime.datetime.timetuple(datetime_replace)
      print(datetime_timetuple, type(datetime_timetuple))
      # ISO标准日期时间格式
      print(datetime.datetime.utcoffset(UTCDateTime))
      # 将日期时间对象转换为ISO标准日期时间格式的字符串
      UTC_ISO_DateTime = datetime.datetime.isoformat(UTCDateTime)
      print(UTC_ISO_DateTime, type(UTC_ISO_DateTime))         # 2022-07-10T19:14:27.001235 
      # 将ISO标准日期时间格式的字符串转换为日期时间类型
      From_UTC_ISO_DateTime = datetime.datetime.fromisoformat('9999-12-31T23:59:59.999999')   # 
      print(From_UTC_ISO_DateTime, type(From_UTC_ISO_DateTime))
      # ISO标准的周内第N天
      # 值的范围是[1,7],1代表周一,7代表周日
      UTC_ISO_WeekDateTime = datetime.datetime.isoweekday(UTCDateTime)
      print(UTC_ISO_WeekDateTime, type(UTC_ISO_WeekDateTime))     # 7 
      # ISO标准的日历时间,Calendar中文释义为日历
      # 各个值的含义为(年份、周数、周内的第N天)即(year, week, weekday);
      # weekday的值为[1,7],1代表周一,7代表周日
      # 示例:datetime.IsoCalendarDate(year=2022, week=27, weekday=7)
      UTC_ISO_CalendarDateTime = datetime.datetime.isocalendar(UTCDateTime)
      print(UTC_ISO_CalendarDateTime, type(UTC_ISO_CalendarDateTime))
      # 将ISO标准日历格式的字符串转换为时间日期型
      From_UTC_ISO_CalendarDateTime = datetime.datetime.fromisocalendar(year=2022, week=27, day=7)
      print(From_UTC_ISO_CalendarDateTime)        # 2022-07-10 00:00:00
      print(type(From_UTC_ISO_CalendarDateTime))  # 
      
      # 日期时间替换函数replace()
      # replace()可以只替换日期时间属性的某一项
      # replace()函数的第一个参数必传
      # replace()函数的第一个参数是一个日期时间类型(datetime.datetime)的对象
      # 按关键字传参替换
      # 按位置传参体换
      datetime_replace = datetime.datetime(year=2022, month=7, day=9, hour=19, minute=14, second=27, microsecond=123)
      # 初始值
      print(f"datetime_replace的原值为:{datetime_replace}", f"类型是:{type(datetime_replace)}")
      # 不传参数
      print(datetime.datetime.replace(datetime_replace))    # 2022-07-09 19:14:27.000123
      # 只替换年份
      print(datetime.datetime.replace(datetime_replace, 2019))    # 2019-07-09 19:14:27.000123
      print(datetime.datetime.replace(datetime_replace, year=2019))   # 2019-07-09 19:14:27.000123
      # 只替换月份, 替换其他参数同理
      print(datetime.datetime.replace(datetime_replace, month=12))            # 2022-12-09 19:14:27.000123
      print(datetime.datetime.replace(datetime_replace, datetime_replace.year, 12))   # 2022-12-09 19:14:27.000123
      # 替换其他参数同理
      print(datetime.datetime.replace(datetime_replace, year=2019, month=12, day=31, hour=15,
                                     minute=13, second=15, microsecond=9999))    # 2019-12-31 15:13:15.00999
      # 日期时间对象格式化strftime()
      # 日期时间对象格式化常用的格式如下:
      ""
      %H(两位数的小时)、%M(两位数的分钟)、%S(两位数的秒)、%f(6位数的微秒)、%h(简写的月份名,一般为英文简写)
      %y(两位数的年份)、%Y(四位数的年份)、%m(两位数的月份)、%d(两位数的天数)
      """
      # 可以只格式化部分属性
      datetime_str = datetime.datetime.strftime(datetime_replace, "%Y-%m-%d %H:%M:%S.%f")
      print(f"格式化后是:{datetime_str}", type(datetime_str))      # 2022-07-09 19:14:27.000123 
      # 格式化日期属性
      datetime_str_date = datetime.datetime.strftime(datetime_replace, "%Y-%m-%d")
      print(f"格式化日期的值为:{datetime_str_date}")      # 2022-07-09
      # 格式时间属性
      datetime_str_time = datetime.datetime.strftime(datetime_replace, "%H:%M:%S.%f")
      print(f"格式化时间的值为:{datetime_str_time}")      # 19:14:27.000123
      ```
      로그인 후 복사

    위 내용은 Python에서 datetime 모듈을 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    본 웹사이트의 성명
    본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

    핫 AI 도구

    Undresser.AI Undress

    Undresser.AI Undress

    사실적인 누드 사진을 만들기 위한 AI 기반 앱

    AI Clothes Remover

    AI Clothes Remover

    사진에서 옷을 제거하는 온라인 AI 도구입니다.

    Undress AI Tool

    Undress AI Tool

    무료로 이미지를 벗다

    Clothoff.io

    Clothoff.io

    AI 옷 제거제

    AI Hentai Generator

    AI Hentai Generator

    AI Hentai를 무료로 생성하십시오.

    뜨거운 도구

    메모장++7.3.1

    메모장++7.3.1

    사용하기 쉬운 무료 코드 편집기

    SublimeText3 중국어 버전

    SublimeText3 중국어 버전

    중국어 버전, 사용하기 매우 쉽습니다.

    스튜디오 13.0.1 보내기

    스튜디오 13.0.1 보내기

    강력한 PHP 통합 개발 환경

    드림위버 CS6

    드림위버 CS6

    시각적 웹 개발 도구

    SublimeText3 Mac 버전

    SublimeText3 Mac 버전

    신 수준의 코드 편집 소프트웨어(SublimeText3)

    Linux 시스템에서 Python 통역사를 삭제할 수 있습니까? Linux 시스템에서 Python 통역사를 삭제할 수 있습니까? Apr 02, 2025 am 07:00 AM

    Linux 시스템과 함께 제공되는 Python 통역사를 제거하는 문제와 관련하여 많은 Linux 배포판이 설치 될 때 Python 통역사를 사전 설치하고 패키지 관리자를 사용하지 않습니다 ...

    파이썬에서 맞춤형 데코레이터의 Pylance 유형 감지 문제를 해결하는 방법은 무엇입니까? 파이썬에서 맞춤형 데코레이터의 Pylance 유형 감지 문제를 해결하는 방법은 무엇입니까? Apr 02, 2025 am 06:42 AM

    Pylance 유형 감지 문제 솔루션 Python 프로그래밍에서 사용자 정의 데코레이터를 사용할 때 Decorator는 행을 추가하는 데 사용할 수있는 강력한 도구입니다 ...

    Python의 HTTPX 라이브러리를 사용하여 HTTP/2 Post 요청을 보내는 방법은 무엇입니까? Python의 HTTPX 라이브러리를 사용하여 HTTP/2 Post 요청을 보내는 방법은 무엇입니까? Apr 01, 2025 pm 11:54 PM

    Python의 HTTPX 라이브러리를 사용하여 HTTP/2를 보내십시오 ...

    Python 3.6 피클 파일로드 오류 modulenotfounderRor : 피클 파일 '__builtin__'를로드하면 어떻게해야합니까? Python 3.6 피클 파일로드 오류 modulenotfounderRor : 피클 파일 '__builtin__'를로드하면 어떻게해야합니까? Apr 02, 2025 am 06:27 AM

    Python 3.6에 피클 파일 로딩 3.6 환경 오류 : ModulenotFounderRor : nomodulename ...

    Fastapi와 Aiohttp는 동일한 글로벌 이벤트 루프를 공유합니까? Fastapi와 Aiohttp는 동일한 글로벌 이벤트 루프를 공유합니까? Apr 02, 2025 am 06:12 AM

    파이썬 비동기 라이브러리 사이의 호환성 문제 파이썬에서 비동기 프로그래밍은 동시성과 I/O의 프로세스가되었습니다 ...

    Python 3.6에 피클 파일을로드 할 때 '__builtin__'모듈을 찾을 수없는 경우 어떻게해야합니까? Python 3.6에 피클 파일을로드 할 때 '__builtin__'모듈을 찾을 수없는 경우 어떻게해야합니까? Apr 02, 2025 am 07:12 AM

    Python 3.6에 피클 파일로드 3.6 환경 보고서 오류 : modulenotfounderror : nomodulename ...

    See all articles