Python标准库datetime之datetime模块用法分析详解

目录
  • 1、日期时间对象
  • 2、创建日期时间对象
    • 2.1、通过datetime.datetime.utcnow()创建
    • 2.2、通过datetime.datetime.today()函数创建
    • 2.3、通过datetime.datetime.now()创建
    • 2.4、通过datetime.datetime()创建
    • 2.5、查看创建的对象
    • 2.6、查看datetime可以处理的最大的日期时间对象及最小的日期时间对象
  • 3、日期事件对象的属性
  • 4、日期时间对象转换为时间元组
  • 5、将日期时间对象转化为公元历开始计数的天数
  • 6、日期时间对象转换为一个日期格式值的字符串

1、日期时间对象

  • 日期时间对象是指具有日期(年月日)和时间(时分秒)双重属性的实例
  • 日期时间对象的类型为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()创建时的参数范围如下
序号 形参 实参范围
1 year 1~9999
2 month 1~12
3 day 0~23
4 hour 0~23
5 minute 0~59
6 second 0~59
7 microsecond 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.datetime.now()创建

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 'datetime.datetime'>
print(datetime_first, type(datetime_first))     # 2022-07-09 18:12:43.486469 <class 'datetime.datetime'>
print(datetime_second, type(datetime_second))   # 2022-07-09 18:12:43.486469 <class 'datetime.datetime'>
print(datetime_three, type(datetime_three))     # 0001-01-01 00:00:00.000001 <class 'datetime.datetime'>
print(datetime_four, type(datetime_four))       # 9999-12-31 23:59:59.999999 <class 'datetime.datetime'>
print(datetime_five, type(datetime_five))       # 9999-12-31 23:59:59.999999 <class 'datetime.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

3、日期事件对象的属性

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 'int'>
"""# 从日期时间对象中获取月份"""
datetime_month = datetime_first.month
print(datetime_month, type(datetime_month))       # 7 <class 'int'>
"""# 从日期时间对象中获取天"""
datetime_day = datetime_first.day
print(datetime_day, type(datetime_day))       # 10 <class 'int'>
"""# 从日期时间对象中获取小时"""
datetime_hour = datetime_first.hour
print(datetime_hour, type(datetime_hour))       # 18 <class 'int'>
"""# 从日期时间对象中获取分钟"""
datetime_minute = datetime_first.minute
print(datetime_minute, type(datetime_minute))       # 56 <class 'int'>
"""# 从日期时间对象中获取秒数"""
datetime_second = datetime_first.second
print(datetime_second, type(datetime_second))       # 16 <class 'int'>
"""# 从日期时间对象中获取微秒"""
datetime_microsecond = datetime_first.microsecond
print(datetime_microsecond, type(datetime_microsecond))       # 735264 <class 'int'>

“”“# 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))”""

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 'time.struct_time'>

5、将日期时间对象转化为公元历开始计数的天数

  • 日期时间对象转化为公元历开始计数的天数
  • 将一个整形数值转换为日期时间对象
  • 整形数值最大值为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 'int'>
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))

6、日期时间对象转换为一个日期格式值的字符串

  • 示例如 Sat Jul 9 19:14:27 2022(2022年7月9日星期六)
  • 第一部分的值代表星期几
  • 第二部分的值代表月份
  • 第三部分的值代表日
  • 第四部分的值代表时间
  • 第五部分的值代表年份
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 <class 'float'>
```
![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 <class 'str'>
# 将ISO标准日期时间格式的字符串转换为日期时间类型
From_UTC_ISO_DateTime = datetime.datetime.fromisoformat('9999-12-31T23:59:59.999999')   # <class 'datetime.datetime'>
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 <class 'int'>
# 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))  # <class 'datetime.datetime'>
```
![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 <class 'str'>
# 格式化日期属性
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 'datetime.datetime'>
print(datetime_first, type(datetime_first))     # 2022-07-09 18:12:43.486469 <class 'datetime.datetime'>
print(datetime_second, type(datetime_second))   # 2022-07-09 18:12:43.486469 <class 'datetime.datetime'>
print(datetime_three, type(datetime_three))     # 0001-01-01 00:00:00.000001 <class 'datetime.datetime'>
print(datetime_four, type(datetime_four))       # 9999-12-31 23:59:59.999999 <class 'datetime.datetime'>
print(datetime_five, type(datetime_five))       # 9999-12-31 23:59:59.999999 <class 'datetime.datetime'>
# 查看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 <class 'int'>
"""# 从日期时间对象中获取月份"""
datetime_month = datetime_four.month
print(datetime_month, type(datetime_month))       # 12 <class 'int'>
"""# 从日期时间对象中获取天"""
datetime_day = datetime_four.day
print(datetime_day, type(datetime_day))       # 31 <class 'int'>
"""# 从日期时间对象中获取小时"""
datetime_hour = datetime_four.hour
print(datetime_hour, type(datetime_hour))       # 23 <class 'int'>
"""# 从日期时间对象中获取分钟"""
datetime_minute = datetime_four.minute
print(datetime_minute, type(datetime_minute))       # 59 <class 'int'>
"""# 从日期时间对象中获取秒数"""
datetime_second = datetime_four.second
print(datetime_second, type(datetime_second))       # 59 <class 'int'>
"""# 从日期时间对象中获取微秒"""
datetime_microsecond = datetime_four.microsecond
print(datetime_microsecond, type(datetime_microsecond))       # 999999 <class 'int'>
"""# 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 'time.struct_time'>
# 将日期时间对象转化为公元历开始计数的天数
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 'int'>
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 <class 'float'>
# 将时间戳转换为日期时间对象
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 <class 'str'>
# 将ISO标准日期时间格式的字符串转换为日期时间类型
From_UTC_ISO_DateTime = datetime.datetime.fromisoformat('9999-12-31T23:59:59.999999')   # <class 'datetime.datetime'>
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 <class 'int'>
# 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))  # <class 'datetime.datetime'>

# 日期时间替换函数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 <class 'str'>
# 格式化日期属性
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模块用法分析详解的文章就介绍到这了,更多相关Python datetime模块内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python标准库time使用方式详解

    目录 1.time库 1.1.获取格林威治西部的夏令时地区的偏移秒数 1.2.时间函数 1.3.格式化时间.日期 1.4.单调时钟 1.time库 时间戳(timestamp)的方式:通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量 结构化时间(struct_time)方式:struct_time元组共有9个元素 格式化的时间字符串(format_string),时间格式的字符串 1.1.获取格林威治西部的夏令时地区的偏移秒数 如果该地区在格林威治东部会返回负值(

  • 一篇文章带你了解python标准库--time模块

    目录 1. 调用语法: 2. time概述 3. 时间获取 4. 时间格式化(将时间以合理的方式展示出来) 5. 程序计时应用 6. 示例 总结 Time库是python中处理时间的标准库 1. 调用语法: import time time.<b>() 计算机时间的表达,提供获取系统时间并格式化输出功能 提供提供系统精确即使功能,用于程序性能分析 2. time概述 time库包括三类函数 时间获取: time() ctime() gmtime() 时间格式化: strftime() strp

  • Python标准库之time库的使用教程详解

    目录 1.时间戳 2.结构化时间对象 3.格式化时间字符串 4.三种格式之间的转换 time模块中的三种时间表示方式: 时间戳 结构化时间对象 格式化时间字符串 1.时间戳 时间戳1970.1.1到指定时间到间隔,单位是秒 import time print(time.time()) 输出: 1649834054.98593 计算一个小时之前的时间戳 #计算一个小时之前的时间戳 print(time.time() - 3600) 输出: 1649830637.5699048 2.结构化时间对象

  • python标准库之time模块的语法与简单使用

    目录 表示时间的方式 1. 调用语法: 2. time概述 3. 时间获取 4. 时间格式化(将时间以合理的方式展示出来) 5. 程序计时应用 6. 示例 总结 表示时间的方式 时间戳表示法: 即以整型或浮点型表示的是一个以秒为单位的时间间隔.这个时间的基础值是从1970年的1月1号零点开始算起. 格式化的时间字符串: 即以格式化字符串的格式输出时间形式. 元组格式表示法: 即一种Python的数据结构表示.这个元组有9个整型内容(不能少),分别表示不同的时间含义. 索引(Index) 属性(A

  • 一篇文章带你了解python标准库--datetime模块

    目录 1. datetime模块介绍 1.1 datetime模块包含的类 1.2 datetime模块中包含的常量 2. datetime实例的方法 3. 日期格式化符号 总结 1. datetime模块介绍 1.1 datetime模块包含的类 1.2 datetime模块中包含的常量 2. datetime实例的方法 案例代码 import locale from datetime import datetime,date,time locale.setlocale(locale.LC_C

  • 详解Python常用标准库之时间模块time和datetime

    目录 time时间模块 time -- 获取本地时间戳 localtime -- 获取本地时间元组(UTC) gmtime -- 获取时间元组(GMT) mktime -- 时间元组获取时间戳 ctime -- 获取时间字符串 asctime -- 时间元组获取时间字符串 strftime -- 格式化时间 strptime -- 格式化时间 sleep -- 时间睡眠 perf_counter -- 时间计时 模拟进度条 程序计时 时间转换示意图 datetime时间模块 date类 time

  • Python标准库datetime之datetime模块用法分析详解

    目录 1.日期时间对象 2.创建日期时间对象 2.1.通过datetime.datetime.utcnow()创建 2.2.通过datetime.datetime.today()函数创建 2.3.通过datetime.datetime.now()创建 2.4.通过datetime.datetime()创建 2.5.查看创建的对象 2.6.查看datetime可以处理的最大的日期时间对象及最小的日期时间对象 3.日期事件对象的属性 4.日期时间对象转换为时间元组 5.将日期时间对象转化为公元历开始

  • 用python标准库difflib比较两份文件的异同详解

    [需求背景] 有时候我们要对比两份配置文件是不是一样,或者比较两个文本是否异样,可以使用linux命令行工具diff a_file b_file,但是输出的结果读起来不是很友好.这时候使用python的标准库difflib就能满足我们的需求. 下面这个脚本使用了difflib和argparse,argparse用于解析我们给此脚本传入的两个参数(即两份待比较的文件),由difflib执行比较,比较的结果放到了一个html里面,只要找个浏览器打开此html文件,就能直观地看到比较结果,两份文件有差

  • 使用Python标准库中的wave模块绘制乐谱的简单教程

    在本文中,我们将探讨一种简洁的方式,以此来可视化你的MP3音乐收藏.此方法最终的结果将是一个映射你所有歌曲的正六边形网格地图,其中相似的音轨将处于相邻的位置.不同区域的颜色对应不同的音乐流派(例如:古典.嘻哈.重摇滚).举个例子来说,下面是我所收藏音乐中三张专辑的映射图:Paganini的<Violin Caprices>.Eminem的<The Eminem Show>和Coldplay的<X&Y>. 为了让它更加有趣(在某些情况下更简单),我强加了一些限制.

  • Python标准库之Math,Random模块使用详解

    目录 数学模块 ceil -- 上取整 floor -- 下取整 四舍五入 pow -- 幂运算 sqrt -- 开平方运算 fabs -- 绝对值 modf -- 拆分整数小数 copysign -- 正负拷贝 fsum -- 序列和 pi -- 圆周率常数 factorial -- 因数 随机模块 random -- 获取 0~~1 之间的小数 randrange -- 获取指定范围内的整数 randint -- 获取指定范围整数 uniform -- 获取指定范围内随机小数(左闭右开) c

  • python标准库学习之sys模块详解

    目录 前言 处理命令行参数 sys.exit(n) 退出程序,正常退出时exit(0) sys.version 获取Python解释程序的版本信息 sys.platform 返回操作系统平台名称 sys.stdin.readline()与input sys.stdout与print 总结 补充:sys 模块的实例 前言 sys模块是与python解释器交互的一个接口.sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分. 处理命令行参数 在解释器启动后, argv 列表包含

  • Python3标准库之functools管理函数的工具详解

    1. functools管理函数的工具 functools模块提供了一些工具来调整或扩展函数和其他callable对象,从而不必完全重写. 1.1 修饰符 functools模块提供的主要工具就是partial类,可以用来"包装"一个有默认参数的callable对象.得到的对象本身就是callable,可以把它看作是原来的函数.它与原函数的参数完全相同,调用时还可以提供额外的位置或命名函数.可以使用partial而不是lambda为函数提供默认参数,有些参数可以不指定. 1.1.1 部

  • python 第三方库的安装及pip的使用详解

    python是一款简单易用的编程语言,特别是其第三方库,能够方便我们快速进入工作,但其第三方库的安装困扰很多人. 现在安装python时,已经能自动安装pip了 安装成功后,我们可以在Scripts 文件夹下看到pip 使用pip 安装类库也比较简单 pip install ... 即可 以上这篇python 第三方库的安装及pip的使用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • 表格梳理python内置数学模块math分析详解

    python内置数学模块math 提供了一些基础的计算功能,下列表达式默认 from math import * 默认输入输出均为一个数字.大部分函数都很直观,望文生义即可. 其他函数 isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) 若 a 和 b 的值比较接近则返回True,否则False. rel_tol 是相对容差,表示a, b之间允许的最大差值.例如,要设置5%的容差,rel_tol=0.05.rel_tol 必须大于0. abs_tol 是最小

  • Python中非常实用的Math模块函数教程详解

    目录 math模块常数 1. 圆周率 2. Tau (τ) 3. 欧拉数 4. 无限 5. 不是数字 算术函数 1. factorial() 2. ceil() 3. floor() 4. trunc() 5. isclose() 幂函数 1. exp() 2. 对数函数 其他重要的math模块功能 由于该math模块与 Python 版本一起打包,因此您不必单独安装它,直接导入: import math math模块常数 Pythonmath模块提供了多种预定义常量.访问这些常量提供了几个优点

  • Python日志打印里logging.getLogger源码分析详解

    实践环境 WIN 10 Python 3.6.5 函数说明 logging.getLogger(name=None) getLogger函数位于logging/__init__.py脚本 源码分析 _loggerClass = Logger # ...略 root = RootLogger(WARNING) Logger.root = root Logger.manager = Manager(Logger.root) # ...略 def getLogger(name=None): "&quo

随机推荐